What is a Process Memory Layout?
Process memory layout and dynamic allocation, told as a story about dividing one car's workspace into fixed zones.
The car has a bay, but it's unclear where anything goes.Where do the blueprint, parts, and temp table go?
Put the blueprint and parts anywhere, and they get jumbled.A fixed rule for dividing the space is needed.
Process memory layout is the rule that splits the workspace into fixed zones.Each zone has a fixed job, so nothing gets mixed up.
In this picture (low addresses on top), the heap grows down and the stack grows up.When the gap between heap and stack runs out, memory runs out.
Dynamic allocation is handy, but you must return the space when done.Give back what you take from the heap, or the workspace runs short.
A process memory layout fixes zones — code, data, heap, stack — for the workspace, and dynamic memory allocation is borrowing from the heap as needed, then giving it back.
A process's virtual memory is typically laid out, from low addresses up, as the code (text) segment, the data/BSS segment for initialized and uninitialized global variables, the heap which grows via malloc/new during execution, and the stack which grows and shrinks with each function call. The heap grows from low to high addresses while the stack grows from high to low, each toward the other; when the gap between them runs out, an out-of-memory error results. Real operating systems use stack-size limits and guard pages to stop them before they touch. Failing to release dynamically allocated memory with free()/delete accumulates as a memory leak.
When grown-ups say it
- Code (Text) Segment
- The zone holding the unchanging blueprint. Holds the program's instructions.
- Data/BSS Segment
- The zone for globally prepared parts. Split by whether the value is initialized.
- Heap
- The warehouse you draw more from as needed. Grows from low to high addresses.
- Stack
- The temp table that piles up and clears with each call. Grows from high to low addresses.
- Dynamic Memory Allocation
- Borrowing as much as needed from the heap. Borrowed with malloc/new, returned with free/delete.
- Memory Leak
- Space that piles up because it's never returned. Slows down long-running programs.
- Stack Overflow
- The temp table (stack) spilling past its set limit. Common with excessively deep recursion.
- Heap-Stack Collision
- Heap and stack growing toward each other until they collide. Once the space between them runs out, no memory is left to use.