C++ · Module 7 · Lesson 12 min read

The Memory Model: Stack & Heap

Memory as numbered boxes

RAM is a long row of bytes, each with an address (a number, usually shown in hex like 0x7ffd5c3a). A variable occupies one or more consecutive bytes; its address is where it starts.

The main regions of a program

RegionHoldsLifetimeManaged by
Code (text)machine instructionswhole programOS
Static/global dataglobals, static variables, string literalswhole programcompiler
Stacklocal variables, function parameters, return addressesuntil the function/block endsautomatic
Heap (free store)memory from new / containers' internal buffersuntil releasedyou (or smart pointers/containers)

The stack

  • Each function call pushes a stack frame; returning pops it
  • Extremely fast (just moving a pointer)
  • Limited size (often 1–8 MB) → huge local arrays or deep recursion = stack overflow
  • Variables are destroyed automatically at the end of their scope

The heap

  • Large, flexible, size chosen at runtime
  • Slower to allocate
  • Lives until explicitly released → risk of leaks (forgetting) and dangling pointers (using after release)
  • std::vector, std::string, std::map use the heap internally but manage it for you ✅

Address-of operator &

&x gives the address of x. (Addresses change every run because of security features like ASLR, so programs rarely print them except for learning.)

sizeof vs heap size

sizeof(std::vector<int>) is about 24 bytes no matter how many elements it holds — the elements live on the heap; the vector object stores a pointer, size and capacity.

Rule of thumb ✅

  1. Prefer stack objects and standard containers
  2. If you need heap objects, use smart pointers (Unit 11)
  3. Raw new/delete only when you really know why

Example

C++
#include <iostream>
#include <string>
#include <vector>

int global_counter = 0;                  // static data region

void show_frame(int depth) {
    int local = depth * 10;              // lives in this call's stack frame
    std::cout << "  depth " << depth << ": local = " << local << '\n';
    if (depth < 3) show_frame(depth + 1);
}

int main() {
    int a = 1, b = 2;                    // stack
    std::cout << "a and b are " << sizeof(int) << " bytes each\n";
    std::cout << "&a and &b differ by " << std::abs(reinterpret_cast<char*>(&a) - reinterpret_cast<char*>(&b)) << " bytes\n";

    std::cout << "Recursive calls each get their own frame:\n";
    show_frame(1);

    std::vector<int> small = { 1, 2, 3 };
    std::vector<int> big(1'000'000, 7);  // a million ints, stored on the heap
    std::cout << "sizeof(small) = " << sizeof(small) << ", sizeof(big) = " << sizeof(big)
              << " (the elements are on the heap)\n";
    std::cout << "big really holds " << big.size() * sizeof(int) << " bytes of data\n";

    std::string short_text = "hi";
    std::string long_text(100, 'x');
    std::cout << "sizeof(std::string) = " << sizeof(std::string) << " for both "
              << short_text.size() << " and " << long_text.size() << " characters\n";

    int* heap_number = new int(42);      // raw heap allocation (shown once, avoid in real code)
    std::cout << "heap value: " << *heap_number << '\n';
    delete heap_number;                  // must release it ourselves
    ++global_counter;
    std::cout << "global_counter = " << global_counter << '\n';
    return 0;
}

/* Output:
a and b are 4 bytes each
&a and &b differ by 4 bytes
Recursive calls each get their own frame:
  depth 1: local = 10
  depth 2: local = 20
  depth 3: local = 30
sizeof(small) = 24, sizeof(big) = 24 (the elements are on the heap)
big really holds 4000000 bytes of data
sizeof(std::string) = 32 for both 2 and 100 characters
heap value: 42
global_counter = 1
*/