Loading lessons...
The Stack and the Heap
The Stack and the Heap
Two regions of memory do very different jobs. Understanding their differences explains most performance and bug stories in C++.
The stack
The stack is where the compiler saves function calls and local variables. Calling a function pushes a new frame; returning pops it off:
void bar() { int b = 2; } // b lives only inside bar
void foo() {
int a = 1; // a lives only inside foo
bar(); // stack grows, then shrinks
}
- It grows when you call a function and shrinks when it returns.
- Space is allocated almost for free because the same area is reused.
- It is small by default - pile up too much (like a huge local array or runaway recursion) and you get a stack overflow.
- Because it grows and shrinks automatically, it's the home of automatic variables.
The heap
The heap is the large shared pool of memory you can grab at any time:
int* p = new int; // take heap memory whenever you like
- Allocation is manual and slower than the stack: the runtime has to find a free block, track it, and free it later.
- It can hold huge amounts and live across scopes - that's why dynamic arrays and big data live here.
- Freeing is manual, which is why leaks and dangling pointers happen here.
Address growth
A fun detail: on most systems the stack grows down in memory (new frames get lower addresses), while the heap grows up (higher addresses) as allocations happen. For example, allocate two ints on the heap and the second may get a higher address than the first.
TL;DR
- Stack frames are pushed when you call and popped when you return.
- Stack is small, automatic, and super fast.
- Heap is for manual, large, long-lived data; it's slower to allocate.
- Stack and heap grow in opposite directions in most implementations.
- Runaway recursion or huge locals cause a stack overflow.