Variables, addresses and bytes
A variable is a few bytes at an address. A string is bytes ending in zero. malloc hands you bytes that are yours until you free them.
- Read a variable's value, address and byte layout
- Explain why a three-letter string needs four bytes
- Tell stack memory from heap memory, and know when each is released
The first program is short, but almost everything in C is already in it:
int lucky = 23;
printf("value: %i \n", lucky); // print value
printf("value: %p \n", &lucky); // print address in memory
char *str = malloc(4);
str[0] = 'h';
str[1] = 'e';
str[2] = 'y';
str[3] = '\0';
free(str);
Step through it and watch the bytes:
Values have bytes and addresses
int lucky = 23 reserves four bytes (on every mainstream platform) and stores 23 in them. In hexadecimal 23 is 0x17, and x86 and ARM store the least significant byte first, so memory holds 17 00 00 00. &lucky is the address of the first of those bytes, which %p prints. Strictly, %p expects a void *, so the portable spelling is printf("%p", (void *)&lucky).
Run the program twice and the address changes: the operating system places the stack at a random location each run (address-space layout randomisation), which makes many memory-corruption attacks harder.
Strings end in a zero byte
C has no string type. A string is an array of char that ends with the byte 0, written '\0'. Functions like printf("%s") and strlen walk forward until they find it, so "hey" needs four bytes: 68 65 79 00. Forget the terminator and those functions run on into whatever memory follows.
Stack and heap
lucky and str are local variables. They live in main’s stack frame and disappear when main returns — automatically. The four bytes from malloc live on the heap, and stay allocated until free is called, however many functions return in between. That is the whole point of the heap, and the whole danger: forget free and memory leaks; use the pointer after free and the program reads memory that may already belong to something else.
After free(str), str still holds the old address. It is now a dangling pointer. A common defensive habit is free(str); str = NULL;, so a later mistake crashes immediately instead of quietly corrupting data.
One more habit: malloc returns NULL when it cannot allocate. Real code checks before writing through the pointer, as lesson 3’s create_human does.
Try it yourself. Print sizeof(lucky), sizeof(str) and sizeof(char). Then add a loop that prints each byte of lucky with unsigned char *b = (unsigned char *)&lucky; and check the little-endian order. Finally, comment out str[3] = '\0';, add printf("%s\n", str); before the free, and build with gcc -fsanitize=address to see the overrun reported.