The Runtime Theory
C++

Stack vs Heap: Where Memory Lives

Understand the difference between stack memory (fast, automatic) and heap memory (dynamic allocation), and when to use each.

The Runtime Theory Team1 min read
▸ On this page

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.

cpp
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
ProsCons
Very fast allocation (single CPU instruction)Limited size (typically 1–8 MB)
Automatic cleanup when function returnsSize 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.

cpp
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;
}
ProsCons
Large (limited only by available RAM)Slower allocation (requires bookkeeping)
Size determined at runtimeMust be freed manually (or use smart pointers)
Persists beyond function scopeFragmentation 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_ptr and std::shared_ptr for heap allocation to avoid memory leaks.

Memory Layout

plaintext
High Address
┌─────────────┐
│   Stack     │ ← grows down
│   (auto)    │
├─────────────┤
│             │
│   Heap      │ ← grows up
│   (new)     │
├─────────────┤
│   Data      │ ← global/static variables
├─────────────┤
│   Text      │ ← code (read-only)
└─────────────┘ Low Address

Not started

Sign in to save your learning progress.

Sign in to save