Topic 82 of 83
Memory Layout
Overview
A C++ program's memory is divided into segments: Code (instructions), Data (globals/statics), Heap (dynamic memory), and Stack (local variables/function calls). Understanding Stack vs Heap is mandatory for C++ mastery.
Syntax
cpp
void doWork() {
// STACK: Fast, automatic, but very small (usually a few MBs)
int localArray[100];
// HEAP: Slower, manual management, massive (limited by RAM)
int* massiveArray = new int[1000000];
delete[] massiveArray; // Must free Heap memory!
}Common Pitfalls
- Returning a pointer to a Stack variable. The stack is wiped when the function ends, meaning the pointer now points to garbage memory.
Interview Tips
- Stack Overflow: Occurs when you allocate too much on the stack (e.g., a massive array) or have infinite recursion, blowing past the tiny stack limit.
- Heap Fragmentation: Allocating and freeing many small objects randomly leaves 'holes' in RAM, making it hard to allocate large contiguous blocks later.
Real-World Example
Visualizing the layout.
example
cpp
/*
High Memory Addresses
+------------------+
| STACK | <- Local variables, function params. Grows downward.
| | |
| V |
| |
| ^ |
| | |
| HEAP | <- Dynamic memory (new). Grows upward.
+------------------+
| BSS / Data Seg. | <- Global and Static variables
+------------------+
| Code / Text | <- Compiled machine instructions
+------------------+
Low Memory Addresses
*/