Skip to main content
Be Bitwise

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:

SegmentContentsCharacteristics
TextMachine code instructionsRead-only, fixed size
DataInitialised global/static variablesRead-write, fixed size
BSSUninitialised global/static variablesRead-write, zeroed at startup
HeapDynamically allocated memoryGrows upward, managed by programmer
StackLocal variables, function call infoGrows 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.

Key Concept

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

0xFFFF...0x0000...StackgrowsFree SpaceHeapgrowsBSSDataText

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 itThe exact addresses change between runs because of address randomisation, but the order stays the same.
C (GCC 9.2.0)