Memory, the Stack & the Heap

Difficulty
Importance

The problem

Every running program needs somewhere to keep its data, and different kinds of data have very different lifetimes — a function's local variables disappear when it returns, while an object you create might need to outlive the function that created it. Programs need two different memory regions with two different rules to serve both needs.

Why now

Recursion already relies on 'the call stack' informally; arrays and lists already rely on memory existing somewhere. This topic makes that informal reliance precise — showing exactly what the stack and heap are, why recursion has a depth limit, and why some values can be returned safely from a function while others can't.

Mental model

The stack is a tightly disciplined pile of function-call frames — push on call, pop on return, strictly LIFO, which is why deep recursion can overflow it. The heap is a loosely organized pool where anything with an unpredictable lifetime lives, managed by allocation and (in garbage-collected languages) automatic reclamation once nothing references it anymore.

Requires

Helps

Unlocks

Used in

Projects

  • Write a recursive function with no base case and observe the stack overflow error and its message directly
  • Diagram, by hand, the stack frames and heap allocations created by a small program with a few function calls and one closure

Examples

  • A local number variable is pushed onto the stack frame and destroyed automatically when the function returns
  • An object returned from a function must live on the heap, because its lifetime outlives the stack frame that created it

Resources

Mastery checklist