Topic 15 of 15 · Expert
Undefined Behaviour & Memory Layout
Text/data/BSS/heap/stack, UB traps and debugging tools.
Concept
A running C program's memory has segments: text (code), data (initialised globals), BSS (zeroed globals), heap (malloc, grows up) and stack (locals, grows down).
Undefined behaviour — out-of-bounds access, signed overflow, use-after-free, unsequenced modifications — lets the compiler do anything, and optimised builds often 'break' such code.
Compile with -Wall -Wextra -fsanitize=address,undefined and use gdb/Valgrind to catch problems early.
Cheat sheet
| Segment | Holds |
|---|---|
| Text | Machine code (read-only) |
| Data | Initialised globals/statics |
| BSS | Uninitialised globals/statics |
| Heap | malloc'd memory |
| Stack | Locals, return addresses |
Code (C17)
#include <stdio.h>
int g_init = 5; /* data */
int g_zero; /* BSS */
int *bad(void) {
int local = 42;
return &local; /* UB: returns address of dead stack variable */
}
int main(void) {
int a[3] = {1, 2, 3};
/* a[3] = 4; UB: out of bounds */
printf("%d %d\n", g_init, g_zero);
return 0;
}
/* gcc -Wall -Wextra -g -fsanitize=address,undefined app.c */Remember
- Never return addresses of locals.
- Signed overflow is UB; unsigned wraps.
- Sanitizers catch bugs at run time.
Interview questions
Where are static variables stored?
Initialised statics in the data segment; uninitialised (zero) ones in BSS — not on the stack.
What is a segmentation fault?
The OS stops the program for accessing memory it isn't allowed to — e.g. NULL dereference, freed memory or stack overflow.
Lesson test
Take an 8-question test on “Undefined Behaviour & Memory Layout” — concepts, output prediction, bug spotting and interview questions.