Skip to content

1.4 References: using data without taking cleanup responsibility

The minimal model from the previous section rests on two rules: when a stack variable leaves scope (}), the heap allocation it manages is freed automatically; when a value carrying cleanup responsibility is assigned, it moves—transferring both the value and cleanup duty to the new variable while invalidating the original. Now put those two rules to work in an everyday function call.

The pass-by-value dilemma: reading once consumes the argument

Section titled “The pass-by-value dilemma: reading once consumes the argument”

Suppose we write a read-only helper print_it that mutates nothing—it takes a dynamic string s, prints it once, and returns so the caller can print s a second time:

fn print_it(msg) {
print(msg)
} // ← msg leaves scope here
{
s = alloc_heap("hello")
print_it(s)
print(s) // ← can we still use s here?
}

Step through print_it(s) under the rules established so far:

  1. Passing an argument is an assignment: calling print_it(s) binds the argument s to the parameter msg (msg = s).
  2. A move occurs: because the string manages a heap buffer, msg = s follows move semantics, transferring the value and cleanup duty into msg while invalidating s in the caller.
  3. Returning frees the heap buffer: as soon as print_it finishes printing and returns, msg leaves the function’s scope and immediately returns "hello" to the allocator.
  4. The caller cannot continue: back in the outer block, s is invalid and the character buffer on the heap has already been destroyed.

Without changing the model, keeping the string usable after print_it requires returning the parameter out of the function and rebinding it at every call site:

fn print_it(msg) {
print(msg)
return msg // ← forced to move the value back out after reading
}
{
s = alloc_heap("hello")
s = print_it(s) // ← every call must catch the returned value
print(s)
}

If a function needed to inspect three strings and compute a result, it would have to take three parameters and return a four-element tuple (result, s1, s2, s3) for the caller to unpack. Move semantics alone cannot support ordinary function composition.

The bottleneck is that reading data and taking cleanup responsibility are bundled together: to let print_it read the characters, the caller has to hand over the full three-word header, and cleanup duty travels with it. How can a function reach the data without dislodging s?

Passing an address—and why C raw pointers break the model

Section titled “Passing an address—and why C raw pointers break the model”

Looking back at the layout in The stack and the heap, hardware already offers a natural mechanism: instead of passing the three-word header inside s, take the eight-byte stack address of s and pass that address to the function.

At the machine level, any value storing another memory address is, in the broad sense, a pointer. Given those eight bytes, the function follows the address to s on the stack, then follows ptr inside s to read "hello" on the heap, while the original variable s stays put.

If an eight-byte address is all the hardware needs, why not adopt C-style pointers directly?

Because a pointer in C is an unrestricted raw pointer. At the hardware level, holding the stack address of s lets code reach every byte inside it—and a raw pointer imposes zero compile-time rules on what code does next:

  1. Cleanup responsibility breaks down: a raw pointer makes no distinction between the owner of a resource and a temporary reader. A function holding a raw pointer to s can read the heap address inside it and call free early, or copy the three-word header bitwise into a new variable—shattering the single-cleanup invariant from the previous section and bringing double frees right back.
  2. Addresses and mutation go unchecked: a raw pointer can hold a null address (NULL), add arbitrary integer offsets into unknown memory, or mutate and reallocate the heap buffer while another part of the program is still reading from the old heap address.

Passing an eight-byte memory address is sound hardware mechanics; what breaks the model is a raw pointer’s lack of compile-time boundaries.

Putting rules on a pointer: references stripped of cleanup duty

Section titled “Putting rules on a pointer: references stripped of cleanup duty”

From a model designer’s perspective, the fix is direct: keep the compact runtime representation of a pointer (one machine word—an eight-byte address on the stack), while revoking a raw pointer’s unchecked privileges at compile time.

Write &s for taking this restricted address of s, and trace what it points to across the stack and heap:

&s stores the stack address of s, so its arrow stops at the stack header; ptr then points to the characters on the heap.
A reference points to variable s on the stackIn the stack frame, the reference &s occupies one machine word containing the stack address of s, with an arrow pointing down to s. Variable s occupies three machine words—ptr, len 5, and cap 5—and is responsible for freeing the heap. A second arrow runs from ptr to five characters on the heap. The reference arrow stays on the stack.stack frame&sreference (no cleanup duty)stack address of spoints to ssoriginal variable (frees heap)ptrlen · 5cap · 5heapcharacter bufferhello

In both physical layout and model responsibility, s and &s divide the work cleanly:

  • Original variable s: holds the full three-word control header (ptr, len, cap) on the stack and bears exclusive responsibility for freeing the heap at scope exit.
  • Restricted address &s: occupies one machine word (eight bytes) on the stack, storing the stack address of s. Reading the characters takes two hops: follow &s to s on the stack, then follow ptr to "hello" on the heap. At compile time, the model attaches strict limits: cleanup duty is stripped away, and access is read-only—you cannot free memory through it, move the value out of s, or perform pointer arithmetic. When a variable holding &s leaves scope, its eight-byte slot vanishes with the stack frame without touching the heap.

Cleanup responsibility remains with s—use the address to read the data; the duty to free it stays with me.

To distinguish it from an unrestricted C raw pointer, we call this restricted pointer—physically an address, logically stripped of cleanup responsibility—a reference.

No cleanup duty means read-only references follow copy semantics

Section titled “No cleanup duty means read-only references follow copy semantics”

Defining a reference as an eight-byte address with no cleanup duty immediately settles how = behaves on it.

Recall why the previous section separated copy from move: because a heap block can be freed only once, values carrying cleanup responsibility must move on assignment, whereas values carrying no heap cleanup responsibility—like integers—follow copy semantics, leaving both variables valid.

Now inspect &s: it occupies eight bytes on the stack and carries zero cleanup responsibility. Even if you copy &s bitwise 100 times, when all 100 reference variables eventually leave their respective scopes, each one discards its eight-byte stack slot without triggering a single heap free. A double free cannot happen.

In this model, read-only references naturally follow copy semantics—like integers, assigning them to new variables or passing them across functions duplicates the eight-byte address while leaving both the original variable and every reference valid.

Rewrite the opening example with references, and the parameter-passing bottleneck disappears:

fn print_it(msg) { // ← receives a reference; takes on no cleanup duty
print(msg)
} // ← msg leaves scope; only the 8-byte stack address is reclaimed, heap stays intact
{
s = alloc_heap("hello")
print_it(&s) // ← pass the restricted address of s
r1 = &s // ← copy the 8-byte address (copy semantics)
r2 = &s // ← copy the address again; multiple read-only references coexist
print(s) // ← s was never moved and remains readable
} // ← s alone leaves scope here and frees the heap allocation once

The remaining hazard: physically, it is still an address

Section titled “The remaining hazard: physically, it is still an address”

Adding references gives our automatic reclamation model two capabilities at once:

  1. Single, deterministic cleanup: each heap allocation belongs to one original variable (such as s) and is freed automatically at }, with no GC and no double frees.
  2. Zero-copy reading and sharing: read-only callers pass &s, copying an eight-byte address without moving the original variable or cloning heap data.

Stripping away cleanup duty only prevents a reference from freeing someone else’s memory. Remember what a reference still is at runtime: an eight-byte pointer holding a stack address, while s alone decides when the underlying data is freed. Push that fact one step further, and one final safety gap comes into view: when the original variable and a reference live in different scopes, what happens if the original variable leaves scope and frees the data first while an outer reference is still holding the old address?

Carry that question into the next section.