M02 · Memory Model

The Call Stack and the Heap: Frames, Objects and Stack Overflow

Every running call keeps a frame on the call stack for its parameters and local variables, and the frame disappears when the call returns. Objects whose lifetime is not tied to one call live on the heap. Seeing both at once explains why returning frees some memory instantly, why other memory lingers, and why deep recursion can crash a program.

~30 minBeginnerC# · Python · Java · C++
Curriculum: M02 Memory Model · 5 of 5 lessons available

You will be able to

  • Describe what a stack frame holds and why pushing and popping one is cheap.
  • Explain which data dies with a frame and which survives on the heap, and why.
  • Predict when an object becomes unreachable after a return, and what each runtime then does with it.
  • State what happens on stack overflow in C#, Python, Java and C++.

Helpful before this lesson

  • M01 Algorithmic Thinking — Turn a vague task into precise inputs, outputs and constraints, then argue that a solution is correct.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

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:

  1. Each call pushes a frame holding k (a copied value) and list (a copy of the reference, or in C++ a reference parameter that names main's vector).
  2. The list survives every return, because main's frame still refers to it.
  3. 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_ptr is 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.

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 new or std::make_unique have dynamic storage duration and live until something destroys them. Prefer owners (std::unique_ptr, containers) over raw new and delete.

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 using or try-with-resources.
  • Catching StackOverflowError or RecursionError instead 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.

Full implementation

The recursive program in four languages for depths 0 to 5, each checking the resulting list; Java and Python also check that runaway recursion throws (StackOverflowError, RecursionError), CPython that a Box is freed when its frame returns, and C++ that unique_ptr destroys at scope end.

namespace Bekadan.Dsa.Examples.Memory;
 
/// <summary>A small heap object that only one call frame refers to.</summary>
public sealed class Box(int value)
{
    public int Value { get; } = value;
}
 
/// <summary>
/// The Memory Lab's stack-and-heap program: each call gets a frame for its parameters
/// and locals; objects created with new live on the heap until nothing refers to them.
/// </summary>
public static class StackAndHeap
{
    public static List<int> Run(int depth)
    {
        var items = new List<int>();   // the list is on the heap; items (a reference) is in Run's frame
        Fill(items, depth);
        Check(items.SequenceEqual(Enumerable.Range(1, depth).Reverse()), "items == [depth, ..., 1]");
        return items;
    }
 
    private static void Fill(List<int> list, int k)
    {
        if (k == 0) return;
        var box = new Box(k);          // only this frame refers to the Box
        list.Add(box.Value);           // list is a copy of the reference: same List object
        Fill(list, k - 1);
    }                                  // frame popped: the Box is unreachable, the GC reclaims it later
 
    // Too deep a recursion overflows the stack. In .NET a StackOverflowException
    // cannot be caught: the process terminates. So this file does not demonstrate it.
 
    private static void Check(bool condition, string claim)
    {
        if (!condition) throw new InvalidOperationException($"Claim failed: {claim}");
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Memory/StackAndHeap.cs

"""Call frames and heap objects: each call gets a frame; objects live while something refers to them."""
 
import weakref
 
 
class Box:
    def __init__(self, value: int) -> None:
        self.value = value
 
 
def _check(condition: bool, claim: str) -> None:
    if not condition:
        raise AssertionError(f"Claim failed: {claim}")
 
 
def run(depth: int) -> list[int]:
    """The Memory Lab's stack-and-heap program."""
    items: list[int] = []  # the list object; items is a name in run's frame
    fill(items, depth)
    _check(items == list(range(depth, 0, -1)), "items == [depth, ..., 1]")
    return items
 
 
def fill(lst: list[int], k: int) -> None:
    if k == 0:
        return
    box = Box(k)  # only this frame refers to the Box
    lst.append(box.value)  # lst names the caller's list object
    fill(lst, k - 1)
    return  # frame popped: the Box's reference count drops to 0
 
 
def box_freed_on_return() -> bool:
    """True when the Box is gone as soon as its frame is (CPython's reference counting)."""
    probes: list[weakref.ref[Box]] = []
 
    def make() -> None:
        box = Box(1)
        probes.append(weakref.ref(box))
 
    make()
    return probes[0]() is None
 
 
def _runaway(n: int) -> int:
    return _runaway(n + 1)
 
 
def overflow_raises() -> bool:
    """Unbounded recursion raises RecursionError (past sys.getrecursionlimit()), an ordinary exception."""
    try:
        _runaway(0)
    except RecursionError:
        return True
    return False

Tested on CPython 3.14.0 · examples/python/dsa_examples/memory_stack_heap.py

package dev.bekadan.dsa.memory;
 
import java.util.ArrayList;
import java.util.List;
 
/**
 * Call frames and heap objects: each call gets a frame for its parameters and locals;
 * objects created with new live on the heap until nothing refers to them.
 */
public final class StackAndHeap {
    private StackAndHeap() {
    }
 
    /** A small heap object that only one call frame refers to. */
    public static final class Box {
        public final int value;
 
        public Box(int value) {
            this.value = value;
        }
    }
 
    public static List<Integer> run(int depth) {
        List<Integer> items = new ArrayList<>();   // the list is on the heap; items is in run's frame
        fill(items, depth);
        check(items.equals(descending(depth)), "items == [depth, ..., 1]");
        return items;
    }
 
    private static void fill(List<Integer> list, int k) {
        if (k == 0) return;
        Box box = new Box(k);                      // only this frame refers to the Box
        list.add(box.value);                       // list is a copy of the reference: same list
        fill(list, k - 1);
    }                                              // frame popped: the Box is unreachable, the GC reclaims it later
 
    private static List<Integer> descending(int depth) {
        List<Integer> expected = new ArrayList<>();
        for (int k = depth; k >= 1; k--) {
            expected.add(k);
        }
        return expected;
    }
 
    private static int runaway(int n) {
        return runaway(n + 1);
    }
 
    /** Unbounded recursion throws StackOverflowError, an Error rather than an Exception. */
    public static boolean overflowThrows() {
        try {
            runaway(0);
            return false;
        } catch (StackOverflowError expected) {
            return true;
        }
    }
 
    private static void check(boolean condition, String claim) {
        if (!condition) {
            throw new AssertionError("Claim failed: " + claim);
        }
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/memory/StackAndHeap.java

#pragma once
 
#include <cassert>
#include <cstddef>
#include <memory>
#include <vector>
 
namespace bekadan::dsa::memory {
 
// A small heap object that only one call frame owns.
struct Box {
    int value;
};
 
inline void fill(std::vector<int>& list, int k);
 
// The Memory Lab's stack-and-heap program.
inline std::vector<int> stack_and_heap(int depth) {
    std::vector<int> items;                       // the vector object is in this frame; its elements go in a heap buffer
    fill(items, depth);
    for (int i = 0; i < depth; ++i) assert(items[static_cast<std::size_t>(i)] == depth - i);
    return items;
}
 
inline void fill(std::vector<int>& list, int k) {
    if (k == 0) return;
    auto box = std::make_unique<Box>(Box{k});     // owned by this frame
    list.push_back(box->value);                   // list is a reference: another name for the caller's vector
    fill(list, k - 1);
}                                                 // frame popped: ~unique_ptr frees the Box right here
 
// Destruction is deterministic: it happens when the owner goes out of scope.
struct Tracked {
    explicit Tracked(int* counter) : destroyed(counter) {}
    Tracked(const Tracked&) = delete;
    Tracked& operator=(const Tracked&) = delete;
    ~Tracked() { ++*destroyed; }
    int* destroyed;
};
 
inline bool destroyed_at_scope_end() {
    int destroyed = 0;
    {
        auto owner = std::make_unique<Tracked>(&destroyed);
        assert(destroyed == 0);
    }
    return destroyed == 1;
}
 
// Running out of stack (unbounded recursion) is not defined by the standard; on
// mainstream platforms the process usually crashes. It is not demonstrated here.
 
}  // namespace bekadan::dsa::memory

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/memory/stack_heap.hpp

References