C Programming

What does %08x mean in C?

Break-down:

8 says that you want to show 8 digits

0 that you want to prefix with 0's instead of just blank spaces

x that you want to print in lower-case hexadecimal.

Quick example (thanks to Grijesh Chauhan):

#include <stdio.h>

int main() {

int data = 29;

printf("%x\n", data); // just print data

printf("%0x\n", data); // just print data ('0' on its own has no effect)

printf("%8x\n", data); // print in 8 width and pad with blank spaces

printf("%08x\n", data); // print in 8 width and pad with 0's

return 0;

}

Output:

1d

1d

1d

0000001d

scanf() - take input from the user

The % Format Specifiers

The % specifiers that you can use in ANSI C are:

Usual variable type Display

%c char single character

%d (%i) int signed integer

%e (%E) float or double exponential format

%f float or double signed decimal

%g (%G) float or double use %f or %e as required

%o int unsigned octal value

%p pointer address stored in pointer

%s array of char sequence of characters

%u int unsigned decimal

%x (%X) int unsigned hex value

Remove buffer overflow protection

# echo 0 > /proc/sys/kernel/randomize_va_space

What does the preceding 0x mean in a number?

The corresponding value is in hexadecimal

  • Most x86 architectures store data in little-endian format when it is pushed onto the stack

  • This means that the least significant byte (far right value) gets stored in the lowest memory location

    • characters are stored backwards

argc

argument count (number of arguments; argv[0] is the command itself)

argv

argument vector (variable that stores the command line argument)

segmentation faults

A segmentation fault (aka segfault) is a common condition that causes programs to crash; they are often associated with a file named core. Segfaults are caused by a program trying to read or write an illegal memory location. Program memory is divided into different segments: a text segment for program instructions, a data segment for variables and arrays defined at compile time, a stack segment for temporary (or automatic) variables defined in subroutines and functions, and a heap segment for variables allocated during runtime by functions, such as malloc (in C) and allocate (in Fortran). For more, see What are program segments, and which segments are different types of variables stored in? A segfault occurs when a reference to a variable falls outside the segment where that variable resides, or when a write is attempted to a location that is in a read-only segment. In practice, segfaults are almost always due to trying to read or write a non-existent array element, not properly defining a pointer before using it, or (in C programs) accidentally using a variable's value as an address

Last updated