Mental model
A thread runs with a call stack: a region of memory that grows by one frame per call and shrinks by one frame per return. A frame holds the call's parameters and local variables (plus bookkeeping such as where to return to; the exact contents are up to the compiler and runtime). Because calls finish in the reverse order they started, the frames form a stack: last in, first out.
Allocating a frame is just moving the stack pointer, and freeing it is moving it back. That is why locals are cheap, and why they cannot outlive the call: when the frame is popped, its memory is reused by the next call.
The heap is for data whose lifetime is not tied to one call: objects created with new (or by
Python for every value), the buffers behind lists and vectors, anything that must survive a return.
Heap memory is handed out by an allocator or a garbage-collected runtime and is reclaimed either
explicitly (C++ owners), when nothing refers to it any more (garbage collection), or when its
reference count reaches zero (CPython).
What the lab shows
main creates a list, then calls a recursive Fill(list, k) that, at each level, allocates a small
Box, appends its value to the list and recurses with k − 1. Watch three things:
- Each call pushes a frame holding
k(a copied value) andlist(a copy of the reference, or in C++ a reference parameter that namesmain's vector). - The list survives every return, because
main's frame still refers to it. - Each Box dies with its frame: once the frame is popped, nothing refers to it. What happens next
is the language's business:
- C++: the
std::unique_ptris destroyed with the frame, and its destructor frees the Box at that moment. - CPython: the Box's reference count drops to zero and it is freed immediately. (Other Python implementations, such as PyPy, may free it later.)
- C# and Java: the Box is now garbage. The collector reclaims it whenever it next runs; no code runs at the moment of the return.
- C++: the
Stack overflow
The stack has a fixed maximum size per thread, commonly around 1 MB by default on Windows and often 8 MB for the main thread on Linux; both are configurable. A recursion that goes too deep, or a few huge local arrays, runs out. The lab's teaching stack holds a handful of frames so you can see it happen. Real consequences differ:
| Language | On overflow |
|---|---|
| C# | StackOverflowException, which cannot be caught: the runtime terminates the process. |
| Java | StackOverflowError. It is an Error, so it can be caught, but the program is rarely in a state worth continuing. |
| Python | CPython raises RecursionError once the depth passes sys.getrecursionlimit() (1000 by default). It is an ordinary exception. |
| C++ | The standard does not define it. On mainstream platforms the process usually crashes (for example, a segmentation fault on a guard page). |
The fix is the same everywhere: bound the depth, or turn the recursion into a loop with an explicit stack on the heap.
Language notes
- C#: class instances always live on the managed heap. Struct locals usually live in the frame, but a struct inside an array, a class field, a captured lambda variable or a boxed value lives with that container, so "value types live on the stack" is only a rule of thumb.
- Java: the JVM specification gives each thread its own stack of frames, and objects live on the heap. The JIT may avoid some heap allocations when an object provably never escapes a method, but that is an optimisation, not something your code can observe or rely on.
- Python: every object lives on the heap; a frame holds names bound to those objects.
- C++: variables with automatic storage duration live until the end of their scope; objects from
neworstd::make_uniquehave dynamic storage duration and live until something destroys them. Prefer owners (std::unique_ptr, containers) over rawnewanddelete.
Costs
- Pushing or popping a frame: O(1).
- A recursion of depth d keeps d frames alive at once: O(d) stack space, however little each call does.
- Heap allocation costs more than a frame push (finding space, and later reclaiming it), which is why tight loops avoid allocating.
Common mistakes
- Returning a pointer or reference to a local in C++: the frame is gone after the return.
- Expecting a C# or Java object to be cleaned up at the end of a method. Its memory is reclaimed
later, by the collector; deterministic cleanup needs
usingor try-with-resources. - Catching
StackOverflowErrororRecursionErrorinstead of bounding the recursion. - Raising Python's recursion limit very high: the interpreter's own C stack can still overflow and crash.
Edge cases
- Depth 0 in the lab: one call, the base case, nothing allocated.
- Every thread has its own stack; the heap is shared by all threads of a process.
- Some compilers turn tail calls into jumps, but neither C#, Java nor CPython guarantees it.
Worked practice
1. With depth 3, how many frames exist at the deepest point, counting main?
Answer
Five: main, then Fill with k = 3, 2, 1 and 0. The base case is a call too.
2. After Fill(items, 3) returns in Java, how many Box objects still exist?
Answer
Up to three: all are unreachable, but the garbage collector decides when to reclaim them, so they may still occupy memory. In C++ none remain; in CPython none remain either, because each was freed when its reference count reached zero.
Summary
- One frame per running call; popping it frees its locals instantly.
- Objects that must outlive a call live on the heap.
- An object dies when nothing refers to it (GC, refcount) or when its owner destroys it (C++).
- Stack space is limited; deep recursion overflows, with different consequences per language.