Stack and Heap
The two main regions of program memory: the call stack for function frames and the heap for longer-lived data.
What is it?
A running program uses memory in two main ways.
The call stack tracks the functions currently running. Every call pushes a stack frame holding that call's parameters, local variables and the address to return to. When the function returns, its frame is popped and that memory is instantly reused. Stack memory is fast, automatic and limited in size (often 1–8 MB per thread).
The heap is a large pool for data whose size or lifetime isn't tied to a single call: objects, lists, strings built at run time, anything that must outlive the function that created it. Heap memory is allocated on request and freed later, either by you (C's free), by ownership rules (Rust), or by a garbage collector (Python, JavaScript, Java, Go).
If calls nest too deeply (usually through runaway recursion), the stack runs out of room: a stack overflow.
Explain like I'm 10
The stack is a pile of sticky notes on your desk: each task you start puts a note on top, and you throw it away when the task is done. It's quick but the desk is small. The heap is a warehouse: you can store big things there for as long as you need, but you have to keep track of what's where and someone has to clean it out.
Examples
Frames on the call stack (Python)
def square(n):
result = n * n # 'n' and 'result' live in square's frame
return result
def sum_of_squares(a, b):
return square(a) + square(b)
print(sum_of_squares(2, 3)) # 13Stack overflow from unbounded recursion
function countDown(n) {
return countDown(n - 1); // no base case: never stops
}
countDown(10);
// RangeError: Maximum call stack size exceeded
// Python's equivalent raises:
// RecursionError: maximum recursion depth exceededStack vs heap made explicit (Rust)
fn main() {
let x: i32 = 42; // 4 bytes, stored in main's stack frame
let boxed = Box::new(42); // pointer on the stack, the i32 on the heap
let names = vec!["a", "b"]; // Vec header (ptr, len, cap) on the stack,
// the elements on the heap
println!("{} {} {:?}", x, boxed, names);
} // frame popped; boxed and names free their heap memory hereRust makes the split visible: fixed-size values live on the stack by default, and Box, Vec and String own heap memory that is freed when their owner goes out of scope.
How it works
The stack is a contiguous block with a stack pointer marking the top. Calling a function moves the pointer to reserve space for the new frame; returning moves it back. That's why stack allocation is almost free and locals vanish when their function returns.
The heap is managed by an allocator that finds a free block of the requested size, hands back its address and later reclaims it. That bookkeeping is slower than bumping a pointer, and freed blocks can leave gaps (fragmentation).
What lives where depends on the language:
- C / C++ / Rust: locals and fixed-size values on the stack; malloc, new, Box, Vec, String contents on the heap. - Java: primitive locals and references on the stack; every object (new ...) on the heap. The JIT may still place non-escaping objects on the stack as an optimisation. - Python: every value is a heap-allocated object; frames hold only references to them. - JavaScript: objects, arrays and closures' captured variables are on the heap; the engine decides where primitives go.
High addresses
+---------------------------+
| Stack (grows down) |
| frame: square n=2 | <- top (stack pointer)
| frame: sum_of_squares |
| frame: main |
| | |
| v |
| |
| ^ |
| | |
| Heap (grows up) |
| [list] [User] [string] |
+---------------------------+
| Static data, code |
+---------------------------+
Low addresses (simplified; real layouts vary by OS)Why does it exist?
Most data is temporary and tied to a single function call, so a stack gives it extremely cheap, automatic memory. But some data must outlive its creator, be shared, or have a size only known at run time. The heap covers those cases at the cost of slower allocation and the need to free memory eventually.
When to use it
This model matters when you reason about recursion depth, performance of hot loops (heap allocation and GC pressure), why a returned pointer to a local is a bug in C, why closures keep variables alive, and how memory use grows. In systems languages you choose stack or heap explicitly; in managed languages you mostly need it to understand behaviour and performance.
When not to use it
In Python or JavaScript, don't try to "force" values onto the stack or micro-optimise allocation without measuring: the runtime decides and usually decides well. Don't use deep recursion on unbounded input (tree depth from user data, long linked lists); an explicit stack or a loop avoids the overflow.
Common mistakes
Returning a pointer or reference to a local variable in C/C++. The frame is gone after the return, so the pointer dangles.
Recursing over input of unknown size (a deeply nested JSON document, a long linked list) and hitting a stack overflow in production.
Assuming 'stack' and 'heap' here are the stack and heap data structures. The call stack is LIFO like the data structure, but the memory heap has nothing to do with a binary heap.
Assuming primitives always live on the stack in every language. In Python everything is a heap object; in Java and JavaScript placement is an engine detail.
Allocating huge arrays as local variables in C (
int big[10000000];), which can overflow the stack immediately.
Practice exercises
- Easy:
Draw the call stack, frame by frame, for computing
factorial(4)recursively. Mark when each frame is pushed and popped. - Medium:
Find the maximum recursion depth in your language (Python:
sys.getrecursionlimit(); JavaScript: count until RangeError). Then rewrite a recursive tree depth function to use an explicit stack. - Hard:
In C or Rust, write a function that returns a dynamically sized array built inside it. Explain why it must live on the heap and who is responsible for freeing it.
Interview questions
What is the difference between the stack and the heap?
The stack holds function call frames (parameters, locals, return addresses); it's fast, automatically managed and limited in size. The heap holds dynamically allocated data with flexible size and lifetime; it's larger but slower to allocate and must be freed manually, by ownership rules or by a garbage collector.
What is a stack frame?
The block of stack memory for one function call. It typically holds the arguments, local variables, saved registers and the return address. It's pushed on call and popped on return.
What causes a stack overflow?
Using more stack memory than is available, almost always from recursion that is too deep or never terminates, and occasionally from very large local arrays.
Why is stack allocation faster than heap allocation?
Stack allocation just moves the stack pointer, and freeing happens automatically on return. Heap allocation has to search for a suitable free block, track it, and later reclaim it, possibly with a garbage collector.
Why is returning a pointer to a local variable a bug in C?
The local lives in the function's stack frame, which is released when the function returns. The pointer then refers to memory that will be reused by the next call: a dangling pointer and undefined behaviour.
In Java, where do objects and primitive locals live?
Objects are allocated on the heap. Primitive local variables and references to objects live in the method's stack frame. The JIT can use escape analysis to avoid heap allocation for objects that never leave a method.
Where do values live in Python?
Every value is an object on the heap, including integers. Variables and frames hold references to those objects, and CPython frees objects through reference counting plus a cycle collector.
How can you avoid a stack overflow in deep recursion?
Convert the recursion to a loop with an explicit stack (or queue) on the heap, bound the input depth, or use tail calls in a language that guarantees tail-call optimisation (Python and most JavaScript engines don't).
Does each thread have its own stack?
Yes. Each thread has its own call stack, while the heap is shared by all threads in the process. That's why locals are thread-private but heap objects need synchronisation when shared.