1.2 The stack and the heap: why the heap needs separate cleanup
The previous section set our target: reclaim memory automatically without manual free calls and without runtime scanning or reference counting. To find a deterministic cue for when memory can be freed, we need to look at the two memory regions a running program relies on: the stack and the heap.
These terms describe where bytes live and how they are allocated and reclaimed—not two categories of data types.
The stack: fixed sizes at compile time, reclaimed on return
Section titled “The stack: fixed sizes at compile time, reclaimed on return”Every time a function is called, the CPU carves out a contiguous block of stack memory—a stack frame—to hold that call’s parameters and local variables. The moment the function returns, the entire frame is reclaimed at once, and every local variable inside it disappears. Frames enter and exit in strict last-in, first-out (LIFO) order.
Allocating or reclaiming a stack frame takes little more than moving a stack pointer, keeping overhead minimal. Better yet, returning from the function reclaims the frame automatically, with no extra cleanup code to write.
If stack frames clean themselves up, what stops a program from using only the stack?
For a function that adds two integers a + b, the stack is enough: a and b occupy fixed byte sizes known at compile time, and their frame vanishes on return. Step beyond fixed-size, single-call computations, however, and a stack-only program runs into two hard limits:
- Every local variable on the stack must have a size known at compile time. To emit machine instructions, the compiler must calculate the exact byte size of each stack frame in advance. When data size is determined only at runtime—a line of user input, a network packet, or a dynamically growing list—the compiler cannot reserve a fixed stack slot for it ahead of time.
- Data stored inside a stack frame cannot outlive that call. Returning reclaims the entire frame, so nothing stored directly inside it can remain in place for longer-lived use outside.
Whenever a program handles data whose size is unknown until runtime—or data that must persist beyond a single stack frame—it has to request space on demand from another region of memory: the heap.
The heap: allocated on demand at runtime, reached via a stack pointer
Section titled “The heap: allocated on demand at runtime, reached via a stack pointer”The heap is managed at runtime by a memory allocator. When a program needs space while running, it asks the allocator for a given number of bytes; the allocator locates a large enough contiguous block on the heap, marks it in use, and returns its starting address.
Because that block is dynamically requested from the allocator at runtime, it is not tied to any function call and will not vanish when a function returns. Once the program is done with it, the block must be explicitly returned to the allocator before those bytes can be reused.
This division also explains how the stack and the heap work together. A heap payload has an unknown size at compile time and cannot fit directly into a stack frame, yet the starting address (pointer) returned by the allocator always has a fixed size—eight bytes (one machine word) on a 64-bit platform. Dynamically sized values therefore split naturally into two parts: a fixed-size control header in the stack frame holding the address and metadata, and the variable-sized payload on the heap.
Consider a growable String (named name in the diagram):
On the stack, name occupies a fixed three machine words (24 bytes on a 64-bit target): a pointer to the heap buffer (ptr), the current byte length (len), and the allocated capacity (cap). Because that three-word header has a compile-time known size, it sits directly in the stack frame, while the variable-length character buffer ("Rust") lives on the heap behind ptr.
When a function returns: the stack frame vanishes, the heap stays behind
Section titled “When a function returns: the stack frame vanishes, the heap stays behind”Watch how the two regions diverge at the exact moment a function returns:
During the call, the stack frame holds variable a, pointing to data allocated on the heap. When the function returns, the stack frame—and a along with it—is reclaimed automatically. The heap, however, does not follow the call stack: the heap block remains right where it was, with no stack variable pointing to it anymore.
In short, function-call mechanics already reclaim stack frames automatically, whereas heap buffers require a separate release step. Everything we derive in this chapter comes down to who performs that release and when.
Get the timing of heap cleanup wrong, and one of three classic memory bugs follows:
- Never returned: the stack pointer is gone, leaving the heap block unreachable and unreleased until the process terminates—a memory leak.
- Returned too early: the heap block is returned to the allocator while an old address elsewhere continues reading or writing through it—a dangling pointer.
- Returned twice: the same heap block is freed two times—a double free, which triggers undefined behavior and typically crashes the program.
The clue to automatic cleanup: stack variables have deterministic scope exits
Section titled “The clue to automatic cleanup: stack variables have deterministic scope exits”Languages like Python, Java, and JavaScript hide the boundary between stack and heap behind their runtimes. Before reasoning about Rust’s rules, anchor this side-by-side layout:
| Dimension | Stack | Heap |
|---|---|---|
| What lives here | Compile-time fixed-size values (integers, booleans, and fixed-size headers pointing to the heap) | Payloads whose size is determined at runtime or grows dynamically |
| How it is allocated | Carved out as a stack frame on function entry by moving the stack pointer | Requested on demand from the memory allocator, which returns a starting address |
| How it is reclaimed | Automatic: returning discards the entire stack frame and its local variables | Not automatic: dynamically acquired memory must be explicitly returned to the allocator |
Distill this layout into the three physical facts our chapter model builds upon:
- Values stored directly in local stack slots must have sizes known at compile time; data allocated or grown dynamically at runtime normally places its payload on the heap. (Later, in Strings, we will also meet string literals baked into the executable’s read-only data segment and slice views that own no heap allocation.)
- In this chapter’s local-variable model, heap data is accessed and managed through a fixed-size control header in the stack frame holding the heap block’s starting address.
- Stack frames are reclaimed automatically on return; memory reclamation is fundamentally the problem of who returns dynamically allocated heap blocks and when.
These three facts explain why tracing GC became the mainstream answer: if stack frames come and go while heap blocks stay put, a natural strategy is to run a collector that starts from live stack variables and follows pointers—keeping reachable heap blocks and reclaiming the rest.
If we rule out both manual free calls and runtime scanning or counting, where is the remaining clue?
Look at the link between facts two and three: a heap block has no built-in expiration point of its own, yet the stack variable holding its control header exits at a point known at compile time—the closing brace (}) of its scope. In the next section, we follow that clue to build a minimal GC-free reclamation model.