Stack vs Heap: Where Memory Lives
In C++, memory is organized into two main regions: the stack and the heap.
The Stack
The stack is a region of memory that stores variables created by each function call. It is extremely fast because allocation is just moving the stack pointer.
void foo() {
int x = 42; // allocated on the stack
int arr[100]; // 400 bytes allocated on the stack
}
// When foo() returns, x and arr are automatically freed| Pros | Cons |
|---|---|
| Very fast allocation (single CPU instruction) | Limited size (typically 1–8 MB) |
| Automatic cleanup when function returns | Size must be known at compile time |
| Stored contiguously (cache-friendly) | Can cause stack overflow if too large |
The Heap
The heap is a larger pool of memory for dynamic allocation. Memory on the heap persists until you explicitly free it.
void foo() {
int* p = new int(42); // allocated on the heap
int* arr = new int[100]; // 400 bytes on the heap
delete[] arr; // must free manually
delete p;
}| Pros | Cons |
|---|---|
| Large (limited only by available RAM) | Slower allocation (requires bookkeeping) |
| Size determined at runtime | Must be freed manually (or use smart pointers) |
| Persists beyond function scope | Fragmentation over time |
When to Use Which
- Use the stack for small, fixed-size objects with known lifetimes.
- Use the heap for large, variable-size objects or objects that need to outlive the current scope.
- In modern C++, prefer
std::unique_ptrandstd::shared_ptrfor heap allocation to avoid memory leaks.
Memory Layout
High Address
┌─────────────┐
│ Stack │ ← grows down
│ (auto) │
├─────────────┤
│ │
│ Heap │ ← grows up
│ (new) │
├─────────────┤
│ Data │ ← global/static variables
├─────────────┤
│ Text │ ← code (read-only)
└─────────────┘ Low Address