1.5 Dangling references: guaranteeing that referenced data stays valid
In the previous section, starting from the hardware idea of passing an address, we designed references stripped of cleanup duty: the original variable s remains responsible for freeing the heap, while &s stores an eight-byte address on the stack and leaves the heap untouched on scope exit.
That design left one boundary question open: what happens if the variable responsible for cleanup leaves scope first while an outer scope still holds a reference to it?
When the original variable exits first: an address pointing to freed memory
Section titled “When the original variable exits first: an address pointing to freed memory”No function call is needed to trigger this failure—a nested inner block {} is enough:
{ r; // declare r in the outer block to hold a reference { x = alloc_heap("hello") r = &x // store the stack address of inner variable x in outer variable r } // ← inner block ends; x leaves scope here print(r) // ← read through the address stored in r: what happens?}Trace this block step by step under our current rules:
- Inside the inner block,
xallocates"hello"on the heap and takes responsibility for freeing it at the inner}. r = &xcopies the stack address ofxinto the outer variabler, leaving cleanup duty withx.- Execution hits the inner closing
}:xleaves scope—its"hello"buffer on the heap is immediately returned to the allocator, andx’s stack slot is retired as well (free to be overwritten by later variables; even ifxheld a stack-only integer, its address would become invalid past}). - Back in the outer block,
ris still in scope, its eight stack bytes still holdingx’s old address. On the next line,print(r)follows that address straight into invalidated memory.
When a reference variable remains in scope after the data it points to has been freed, the result is a dangling reference.
Contrast this bug with reading a variable after a move in Copy and move: after a move, the source variable itself is marked invalid; in a dangling reference, the reference variable r is still live—what has already exited and been freed is the target variable x it points to.
Why the runtime cannot step in
Section titled “Why the runtime cannot step in”Confronted with the invalid read at print(r), could the program inspect r at runtime and block the access?
Look back at r’s physical representation: at runtime, r is nothing more than an eight-byte memory address on the stack. Those eight bytes record a location; not a single bit records whether x is still alive. When the CPU executes print(r), it fetches bytes from that address blindly, with no way to tell live memory from freed memory.
Forcing the runtime to prevent that illegal read leaves only two familiar retreats:
- Delay freeing
xbecauserstill points to it: postpone reclamation until every reference stops using the data—handing cleanup timing back to a runtime collector (tracing GC or reference counting) and overturning the “no GC” premise established in The hard triangle. - Maintain a runtime validity table alongside memory: consult a metadata table before every dereference to verify that the target address is still live—attaching extra instructions and storage overhead to every ordinary memory read and breaking our zero-overhead goal.
We can neither delay cleanup nor tax every read at runtime. Every runtime escape hatch is closed.
Closing the gap: detect the risk and reject compilation
Section titled “Closing the gap: detect the risk and reject compilation”With runtime checks ruled out, preserving memory safety leaves a single path forward—push the defense ahead of execution and add a third hard rule to the model:
Whenever reference code carries any risk of dangling, the compiler must detect it at compile time, report an error, and refuse to produce an executable.
A C compiler lets the dangling block above compile cleanly, leaving the memory bug to detonate in production. In our model, rejecting unsafe code at compile time is the safety mechanism itself: because only a bare eight-byte address survives at runtime, every validity proof has to finish before the binary is built.
How can a compiler prove whether a reference will dangle without running the program?
How the compiler checks: comparing two spans
Section titled “How the compiler checks: comparing two spans”Running the code is unnecessary. Walking the static structure of the source file lets the compiler compute two intervals and check whether one fits inside the other:
- The live span of variable
x: from the point wherexis initialized down to the closing}where it leaves scope and is freed. - The valid span of reference
r: fromr = &x, wherertakes the address, down to the last line in the source that readsr(print(r)).
Plot both spans along a timeline, and the boundary between safe and dangling becomes immediate:
- Left diagram (valid): the valid span of
rsits entirely inside the live span ofx—for as long asris used,xhas not yet left scope, so reading through the address is guaranteed safe. - Right diagram (dangling): the valid span of
rextends pastx’s exit—xis freed at the inner}, yet code tries to readrafterward, so the compiler rejects the program on the spot.
Compressed into a single rule: a reference’s valid span must never extend past the live span of the data it points to—a reference cannot outlive its target variable.
Give that span a name: the region of code over which a reference remains valid is its lifetime. In practice, this mechanism has two direct engineering traits:
- Zero runtime overhead: span calculation and comparison happen entirely at compile time. Once verified, lifetime metadata is erased during code generation, leaving a plain eight-byte address at runtime.
- Inferred automatically inside functions: within a function body, the compiler compares variable scopes and last-use positions automatically with no annotations written by hand. Explicit relationship markers are needed only when references cross function signatures or sit inside custom data structures.
Three lines of defense, locked together
Section titled “Three lines of defense, locked together”With compile-time span comparison in place, the automatic memory reclamation model we started building in The hard triangle closes all three lines of defense:
- Stack variables automatically free their heap allocations on leaving scope (
})—eliminating manualfreecalls, runtime GC, and forgotten cleanup on normal control paths. - Values carrying cleanup responsibility follow move semantics on assignment—transferring both value and duty while invalidating the source variable, so every heap block has a single variable responsible for freeing it at any moment.
- References strip away cleanup duty while the compiler verifies their valid spans (lifetimes)—enabling shared read access under copy semantics without cloning heap buffers, while catching dangling references at compile time.
The next section wraps up the chapter: we align each step of our five-part derivation with official Rust terminology and test your judgment on an end-to-end parameter design problem.