Memory Layout
The Stack & The Heap · Memory & Systems track
3 min read
In this module
Anatomy of a Running Program
When the OS loads your program, it doesn't just sling everything into one giant blob. The process's memory gets carved into distinct segments, each with its own job. Get the layout straight in your head and the rest of stack-and-heap stops feeling like magic.
The Five Segments
From low addresses to high addresses, a typical process memory layout looks like this:
| Segment | Contents | Characteristics |
|---|---|---|
| Text | Machine code instructions | Read-only, fixed size |
| Data | Initialised global/static variables | Read-write, fixed size |
| BSS | Uninitialised global/static variables | Read-write, zeroed at startup |
| Heap | Dynamically allocated memory | Grows upward, managed by programmer |
| Stack | Local variables, function call info | Grows downward, managed automatically |
The text segment holds the compiled instructions of your program. It's almost always marked read-only, so a stray pointer can't trample your own code.
The data segment holds globals and statics that got an initial value in source. The BSS (Block Started by Symbol) segment holds globals that were declared but never initialised; the OS zero-fills them at startup.
A running program's memory splits into segments: text (code), data (initialised globals), BSS (uninitialised globals), heap (dynamic allocation), and stack (function calls and locals). Heap grows upward, stack grows downward, and they share the address space between them.
Process Memory Layout
Heap and Stack: A Collision Course
The heap kicks off just past BSS and grows upward into higher addresses. The stack starts up at the top of the address space and grows downward. They march towards each other across a wide expanse of unused virtual memory. Allocate too much on the heap, or nest function calls too deeply, and one of them runs out of headroom.
Why This Matters
Knowing the layout means you can answer "where does this actually live?" without guessing. Local variable inside a function? Stack. Buffer you grabbed with malloc? Heap. String literal baked into the binary? A read-only data section (.rodata on Linux) that sits alongside the text segment. Each region has its own rules about lifetime, speed, and size limits — and the next lessons take them apart one by one.
Put that to the test. The program prints one address from each region in a jumbled order; sort them in your head from lowest to highest, then check your answer against the sorted list it prints underneath.
Try the Simulations
Stack Push & Pop
Push values onto the stack and pop them off. See how the stack pointer moves and LIFO ordering works.
Function Call & Return
Call a function that doubles a value. See how CALL saves the return address and RET jumps back.
Nested Function Calls
Call a function that calls another function. Watch the stack grow with return addresses as calls nest, then unwind as each function returns.