Module 2 · Memory
2.1Stack, heap and lifetime
Every value lives somewhere in memory for some length of time. Learn where local variables live, why the heap exists, how std::vector keeps its elements there, and when C++ destroys each object.
On this page
- Key terms
- In 30 seconds
- Where values live
- Lifetime: when an object is destroyed
- The stack: one frame per function call
- The heap: memory you ask for while running
- A vector is a small handle to a heap block
- Static storage: alive for the whole program
- Which one should I use?
- Under the hood
- Common pitfalls
- Using a variable after its block ends
- Pointing at an object that’s gone
- Recursing too deep
- Try it yourself
Key terms
- address
- The number of a byte in memory. Every object starts at some address.
- scope
- The part of the code where a name can be used: from its declaration to the closing
}of its block. - lifetime
- The time during which an object exists, from when it's created to when it's destroyed.
- stack
- The memory that holds each function call's local variables. It grows when a function is called and shrinks when it returns.
- stack frame
- One function call's slice of the stack: its parameters, its local variables and where to return to.
- heap
- Memory a program asks for while it runs, for data whose size isn't known in advance or that must outlive a function call.
- own
- An object owns memory when it's responsible for freeing it. A
std::vectorowns its heap block. - size and capacity
- A vector's size is how many elements it holds; its capacity is how many fit in its heap block before it needs a bigger one.
struct- A type you define yourself, made of named fields. Module 4 covers it.
- destructor (
~T()) - A function that runs automatically when an object of type
Tis destroyed. - static storage (
static) - Memory for objects that exist for the whole run of the program, like a
staticlocal variable. - stack overflow
- A crash that happens when the stack runs out of room, usually because of very deep recursion.
Every value in your program lives somewhere in memory, and it lives there for a certain time. Where it lives decides how fast it is to create and how big it can be. How long it lives decides when you can safely use it. Most memory bugs in C++ come from getting one of these wrong, so this lesson shows the two main places, the stack and the heap, and exactly when C++ creates and destroys each object.
In 30 seconds
- Local variables live on the stack. Each one is destroyed at the closing
}of the block that declared it. - The heap holds memory a program asks for while it runs. You’ll rarely touch it directly:
std::vectorandstd::stringmanage it for you. - A local
std::vectoris a small object on the stack (24 bytes here) that owns a block of elements on the heap. - When an object is destroyed, its destructor runs. That’s how a vector frees its heap block without any code from you.
Where values live
While your program runs, its memory is one long row of bytes, and each byte has a number called its address. The program splits that memory into areas with different jobs:
- Code: the machine instructions of your functions.
- Static storage: objects that exist for the whole run of the program.
- The stack: the local variables of the functions that are running right now.
- The heap: memory the program asks for, and gives back, while it runs.
You don’t pick an area by name. C++ picks it from how you create the object: a local variable goes on the stack, a static one goes in static storage, and a std::vector puts its elements on the heap.
Lifetime: when an object is destroyed
An object’s lifetime is the time it exists. For a local variable it starts when its declaration runs, and it ends at the closing } of its block. That’s the same } that ends its scope, the part of the code where you can use its name.
To see a lifetime end, you need an object that says something when it’s destroyed. The program below defines a tiny type, Probe, with a struct (Module 4 covers structs properly). The line starting with ~Probe() is its destructor: a function that runs by itself whenever a Probe is destroyed.
#include <print>
struct Probe {
int id;
~Probe() { std::println("Probe {} destroyed", id); }
};
int main() {
Probe first{1};
Probe second{2};
{
Probe inner{3};
std::println("leaving the block");
}
std::println("leaving main");
}Output
leaving the block Probe 3 destroyed leaving main Probe 2 destroyed Probe 1 destroyed
inner is destroyed at the } of its block, before leaving main prints. first and second are destroyed when main ends, in the reverse of the order they were created: the newest object goes first.
Key ideaLifetime ends at the closing brace
A local variable is destroyed at the end of the block that declared it, every time, even if the block exits early with return or break. You never have to remember to clean it up.
The stack: one frame per function call
Each time you call a function, it gets a fresh stack frame: room on the stack for its parameters and local variables. When the function returns, its frame is thrown away. Calling the function again builds a new frame, so its locals start over:
#include <print>
void visit() {
int calls = 0;
calls += 1;
std::println("calls = {}", calls);
}
int main() {
visit();
visit();
}Output
calls = 1 calls = 1
The stack is fast: making room for a frame is usually a single subtraction, and throwing it away a single addition. But it’s small, usually a few megabytes for the whole program, and every local variable’s size must be known when the program is compiled.
The heap: memory you ask for while running
Often you don’t know how much data you’ll have until the program runs: how many reads are in a file, how many pixels are in an image. And sometimes data must outlive the function that made it. The heap handles both. A program asks for a block of heap memory of any size while it runs, and the block stays until the program gives it back.
You rarely ask for heap memory yourself. std::vector (Module 3 covers it in full) asks for a heap block big enough for its elements, asks for a bigger one when it fills up, and gives the memory back when it’s destroyed:
#include <print>
#include <vector>
std::vector<int> squares_up_to(int n) {
std::vector<int> squares;
for (int i = 1; i <= n; ++i) {
squares.push_back(i * i);
}
return squares;
}
int main() {
std::vector<int> result = squares_up_to(5);
std::println("{}", result);
}Output
[1, 4, 9, 16, 25]
squares is a local variable of squares_up_to, but its elements are on the heap, so they survive the end of the function: returning the vector hands its heap block over to result, without copying the elements one by one. Module 4 explains how.
Lesson 2.5, Dynamic memory and RAII, shows new, the low-level way to ask for heap memory, and why modern code leaves it to types like std::vector.
A vector is a small handle to a heap block
A std::vector object itself is small and always the same size. It holds where its heap block is, how many elements it has (its size) and how many fit in the block (its capacity). The elements themselves are on the heap. sizeof gives the size of the object, not of its elements:
#include <print>
#include <vector>
std::vector<int> few = {1, 2, 3};
std::vector<int> many(1'000'000, 7); // one million 7s
std::println("{} {}", sizeof(few), sizeof(many));
std::println("{} {}", few.size() * sizeof(int), many.size() * sizeof(int));Output
24 24 12 4000000
On this platform, both vectors are 24 bytes on the stack. One owns 12 bytes of elements on the heap, the other owns 4 million.
When a vector runs out of room, push_back gets a bigger block, so the capacity is often more than the size:
#include <print>
#include <vector>
std::vector<int> v = {1, 2, 3};
v.push_back(4);
std::println("size {}, capacity {}", v.size(), v.capacity());Output
size 4, capacity 6
A std::string works the same way: a small object that owns its characters on the heap.
#include <print>
#include <string>
std::string dna = "ACGTACGTACGTACGTACGTACGTACGTACGT";
dna += "TTTT";
std::println("{} letters, {} bytes", dna.size(), sizeof(dna));Output
36 letters, 32 bytes
Common pitfallsizeof doesn't count the elements
sizeof(v) is the size of the vector object, 24 bytes here, however many elements it holds. For the bytes the elements take up, write v.size() * sizeof(int).
Static storage: alive for the whole program
Mark a local variable static and it’s created once, the first time its declaration runs, and lives until the program ends. It’s stored in static storage, not in the stack frame, so it keeps its value between calls:
#include <print>
void visit() {
static int calls = 0;
calls += 1;
std::println("calls = {}", calls);
}
int main() {
visit();
visit();
}Output
calls = 1 calls = 2
Variables declared outside every function, called global variables, also live in static storage. Use both sparingly: any function can change them, so they make a program harder to follow.
Which one should I use?
| What | When | Why | How |
|---|---|---|---|
| A local variable (stack) | Almost always: single values, small objects, anything used only inside one function. | Creating it is nearly free, and it’s destroyed for you at the end of its block. | int count = 0; |
| A container (heap, owned for you) | Many elements, a count you only know while running, or a lot of data. | The heap has room for large data, and the container frees it when it’s destroyed. | std::vector<double> values; |
A static variable | Something that must keep its value between calls, like a counter. | It lives for the whole program. | static int calls = 0; |
Rule of thumb: make values local. When you need many of something, put them in a std::vector, which is itself a local variable. Reach for static rarely.
Under the hood
With GCC’s standard library on Linux x86-64, a std::vector<int> holds three addresses of 8 bytes each: the start of the heap block, the end of the elements and the end of the block. Size and capacity are worked out from those. That’s the 24 bytes sizeof reported.
When push_back finds the block full, the vector asks for a new block twice as big, moves the elements into it, and frees the old one. That’s why the capacity jumps (other standard libraries may grow by a different factor):
#include <print>
#include <vector>
std::vector<int> v;
std::vector<std::size_t> capacities;
for (int i = 0; i < 9; ++i) {
v.push_back(i);
capacities.push_back(v.capacity());
}
std::println("{}", capacities);Output
[1, 2, 4, 4, 8, 8, 8, 8, 16]
Moving to a new block is also why a reference to an element breaks after push_back; the References lesson shows the sanitizer catching it.
When the vector is destroyed, its destructor frees the heap block. The stack frame holding the 24-byte vector object disappears when the function returns, like any other local.
A std::string keeps very short text inside the object itself and only uses the heap for longer text. That’s why the example above used 36 letters.
PerformanceStack memory is the cheapest memory
A local variable costs almost nothing to create. A heap block costs a call into the memory allocator, which is far slower. If you fill a vector in a loop and know the final count, v.reserve(n) asks for the whole block once instead of several times.
Common pitfalls
Using a variable after its block ends
A variable declared inside a block can’t be used after its }: its scope has ended, and so has its lifetime.
#include <print>
{
int total = 5;
}
std::println("{}", total);The compiler rejects this
main.cpp: In function ‘int main()’:
main.cpp:6:20: error: ‘total’ was not declared in this scope
6 | std::println("{}", total);
| ^~~~~Declare total before the block if you need it after the block.
Pointing at an object that’s gone
A function’s locals are destroyed when it returns, so returning a reference or a pointer to one hands back something that no longer exists. The References and Pointers lessons show the compiler catching it. The fix is to return by value.
Recursing too deep
Every call needs a new stack frame, and the stack is small. A recursive function that calls itself millions of times deep runs out of stack. This one is correct for small numbers, but sum_to(10'000'000) needs ten million frames at once:
#include <print>
long sum_to(long n) {
if (n == 0) {
return 0;
}
return n + sum_to(n - 1);
}
int main() {
std::println("{}", sum_to(10'000'000));
}This fails when it runs
AddressSanitizer:DEADLYSIGNAL
ERROR: AddressSanitizer: stack-overflow on address 0x… (pc 0x… bp 0x… sp 0x… T0)
#0 sum_to(long) main.cpp:7
… the same call 246 more times
SUMMARY: AddressSanitizer: stack-overflow main.cpp:7 in sum_to(long)AddressSanitizer reports a stack overflow; without it, the program crashes with no explanation. Use a loop instead, which needs one frame however many steps it takes:
#include <print>
long sum_to(long n) {
long total = 0;
for (long i = 1; i <= n; ++i) {
total += i;
}
return total;
}
int main() {
std::println("{}", sum_to(10'000'000));
}Output
50000005000000
The same crash can come from one huge local variable. Keep large data in a std::vector, whose elements are on the heap.
Try it yourself
Try it yourself
next_read_id should hand out a new number on each call: 1, 2, 3. Instead it always returns 1. Fix it by changing one line.
#include <print>
int next_read_id() {
int next = 0;
next += 1;
return next;
}
int main() {
for (int i = 0; i < 3; ++i) {
std::println("read {}", next_read_id());
}
}Expected output
read 1 read 2 read 3
Show a hint
The counter is a local variable, so each call gets a fresh one that starts at 0. One word makes it keep its value between calls.
Show a solution
#include <print>
int next_read_id() {
static int next = 0;
next += 1;
return next;
}
int main() {
for (int i = 0; i < 3; ++i) {
std::println("read {}", next_read_id());
}
}static int next = 0; is created once and lives in static storage for the whole program, not in the stack frame, so each call sees the value the previous call left.
Saved in this browser only.