Memory Lab · simulation 2 of 5
Stack frames and heap objects
Each call pushes a frame for its parameters and locals; objects live on the heap until nothing refers to them. Overflow the teaching stack to see what each runtime does.
The full explanation is in the lesson The call stack and the heap.
What to watch for
- A frame appears on every call and vanishes on every return; the list survives because main still refers to it.
- When a frame pops, its Box becomes unreachable: freed at once in C++ and CPython, left for the collector in C# and Java.
- Lower the stack size below depth + 2 frames to trigger an overflow.
In each language
- C#
- A StackOverflowException cannot be caught; the process terminates.
- Python
- RecursionError after sys.getrecursionlimit() frames (1000 by default); catchable.
- Java
- StackOverflowError, an Error; catchable, but recovery is rarely sound.
- C++
- Not defined by the standard; mainstream platforms usually crash.
The programs
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