Stack vs. Heap
The Stack & The Heap · Memory & Systems track
5 min read
In this module
Choosing the Right Tool
Both the stack and the heap store data for your running program, but they're built around opposite trade-offs. Pick the wrong one and you pay in performance, correctness, or in the kinds of bugs you spend a Saturday tracking down.
Side-by-Side Comparison
| Property | Stack | Heap |
|---|---|---|
| Allocation speed | Extremely fast (pointer adjustment) | Slower (allocator bookkeeping) |
| Deallocation | Automatic on function return | Manual (free) or garbage collected |
| Size limit | Small and fixed (1-8 MB typical) | Limited only by available memory |
| Data lifetime | Lives only until the function returns | Lives until explicitly freed |
| Access pattern | LIFO only | Any order |
| Fragmentation | None | Possible over time |
| Cache behaviour | Excellent (contiguous, predictable) | Variable (scattered allocations) |
When to Use the Stack
Use the stack for data with a clear, short lifetime tied to a function call. Local variables, function parameters, small temporary buffers — all natural stack candidates. If you know the size at compile time and the data won't need to outlive the function, the stack is the obvious home.
When to Use the Heap
Reach for the heap when data needs to outlive its function, when the size only becomes known at runtime, or when the chunk is simply too big for the stack to swallow. Dynamically sized arrays, linked lists, trees, and any data structure that grows and shrinks belong here.
The difference that bites hardest is lifetime. Here's a function that hands back a pointer to an int, first with the int on the stack, then on the heap, read top to bottom as time passes:
The stack version's memory dies the instant the function returns, whatever the caller still holds. The heap version lives exactly as long as you say it does, and no longer: after free, that pointer is just as dangerous as the stack one.
Use the stack for small, short-lived data with known size. Use the heap for large, long-lived, or dynamically sized data. The stack is faster but limited; the heap is flexible but requires careful management.
Common Bugs
Mishandling stack and heap memory produces some of the most notorious bugs in software:
- Stack overflow - too many nested function calls (often runaway recursion) exhaust the stack's fixed space. The program crashes.
- Memory leak - heap memory is allocated but never freed. The program's memory usage grows without bound over time.
- Use-after-free - a program frees heap memory but keeps using the pointer anyway. The data at that address may have been overwritten by a later allocation, producing whatever weird behaviour the new occupant induces.
- Double free - calling
freeon the same pointer twice corrupts the allocator's internal data structures, often leading to crashes or exploitable security holes.
Try naming the bug in each of these before you open the answers. Every one compiles.
/* A */int *make_counter(void) { int count = 0; return &count;}
/* B */void log_line(const char *msg) { char *copy = malloc(strlen(msg) + 1); strcpy(copy, msg); puts(copy);}
/* C */char *buf = malloc(64);free(buf);if (error) free(buf);
/* D */int depth(int n) { return depth(n + 1) + 1;}Show the answers
- A returns the address of a local.
countlives inmake_counter's stack frame, which is gone the moment the function returns, so the caller gets a pointer into memory the next call will reuse. Fix: return the value, ormallocthe counter and make the caller free it. - B leaks. Every call allocates a copy and nothing frees it, so a long-running program's memory use creeps upward forever. Fix:
free(copy)afterputs, or skip the copy entirely. - C is a double free on the error path. Fix: set
buf = NULLstraight after the firstfree(freeing NULL is harmless), or restructure so there's onefree. - D has no base case, so it recurses until the stack runs out and the program dies with a stack overflow (a segmentation fault on Linux). Fix: add a condition that stops the recursion.
These bugs are a major reason Rust enforces strict ownership rules at compile time, and why Go and Java reach for garbage collectors. The underlying stack and heap are identical across languages. What differs is how aggressively the language saves you from yourself.
Try the Simulations
Stack Push & Pop
Push values onto the stack and pop them off. See how the stack pointer moves and LIFO ordering works.
Function Call & Return
Call a function that doubles a value. See how CALL saves the return address and RET jumps back.
Nested Function Calls
Call a function that calls another function. Watch the stack grow with return addresses as calls nest, then unwind as each function returns.