Skip to content

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:

  1. Inside the inner block, x allocates "hello" on the heap and takes responsibility for freeing it at the inner }.
  2. r = &x copies the stack address of x into the outer variable r, leaving cleanup duty with x.
  3. Execution hits the inner closing }: x leaves scope—its "hello" buffer on the heap is immediately returned to the allocator, and x’s stack slot is retired as well (free to be overwritten by later variables; even if x held a stack-only integer, its address would become invalid past }).
  4. Back in the outer block, r is still in scope, its eight stack bytes still holding x’s old address. On the next line, print(r) follows that address straight into invalidated memory.
While the inner block is alive, r points at x on the stack, and x points at the heap data. When the inner block ends, x is gone, the heap data is freed, and r still points at the invalidated stack slot.
A reference outlives the variable it points toTwo states. While the inner block is alive, the outer reference r points at the inner variable x on the stack, and x points at the block of data on the heap. After the inner block ends, x is gone, the heap data is freed, and a dashed arrow still runs from r to the gone inner variable.inner block alivestackrouteraddress of xxinnerptr → heapheapdata ("hello")inner block endedstackrouteraddress of xx has left scopeheapdata ("hello")

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.

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:

  1. Delay freeing x because r still 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.
  2. 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 where x is initialized down to the closing } where it leaves scope and is freed.
  • The valid span of reference r: from r = &x, where r takes the address, down to the last line in the source that reads r (print(r)).

Plot both spans along a timeline, and the boundary between safe and dangling becomes immediate:

The valid span of reference r must fall within the live span of variable x; extending past it creates a dangling reference.
A reference’s valid span must fall within the original variable’s live spanTwo panels. In the legal panel, the reference bar is shorter than variable x’s bar and sits inside it. In the illegal panel, the reference bar runs past the end of variable x’s bar and is drawn dashed.valid (inside)code lines →variable xreference rdangling (past the end)code lines →variable xreference r
  • Left diagram (valid): the valid span of r sits entirely inside the live span of x—for as long as r is used, x has not yet left scope, so reading through the address is guaranteed safe.
  • Right diagram (dangling): the valid span of r extends past x’s exit—x is freed at the inner }, yet code tries to read r afterward, 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:

  1. 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.
  2. 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.

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:

  1. Stack variables automatically free their heap allocations on leaving scope (})—eliminating manual free calls, runtime GC, and forgotten cleanup on normal control paths.
  2. 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.
  3. 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.