1.3 Copy and move: from invalidating variables to move semantics
The previous section ended with a structural clue: a heap allocation has no built-in cleanup moment of its own, whereas the stack variable managing it does. Whenever a function returns or a block closes (}), the exact point where a stack variable leaves scope is fixed at compile time.
Setting real Rust syntax aside, we can turn that clue into a minimal automatic reclamation model—and immediately test it against an everyday assignment (=).
The baseline rule: free the heap when its stack variable leaves scope
Section titled “The baseline rule: free the heap when its stack variable leaves scope”Promote that clue into our model’s first rule:
When a stack variable leaves scope (}), automatically free the heap allocation it points to.
Suppose a block requests a heap buffer and manages it through a stack variable s:
{ s = alloc_heap("hello") // ... read and write s inside this block ...} // ← s leaves scope here; its heap allocation is freed automaticallyAs long as s is the sole variable managing that heap buffer from start to finish, this single rule works cleanly:
- Nobody writes
freeby hand, ruling out leaks caused by forgotten cleanup calls. - Deallocation happens right at
}, determined at compile time with zero runtime scanning or reference counting.
Now test this model with an ordinary assignment statement, =.
Why a single assignment frees the same block twice
Section titled “Why a single assignment frees the same block twice”Start with a plain integer on the stack:
{ a = 1 b = a} // ← b and a leave scope and vanish with the stack frameEvaluating b = a copies the stack bytes of a bitwise into b. Because the integer 1 lives entirely on the stack and owns no heap allocation, a and b end up holding two independent copies of 1. At the closing }, both variables vanish with the stack frame, no heap cleanup runs, and nothing goes wrong.
Next, run the same test on a dynamic string managing a heap buffer:
{ s = alloc_heap("hello") t = s} // ← scope ends: what happens now?As seen in the previous section, this value stores a three-word control header on the stack (ptr, len, and cap), while the character buffer "hello" sits on the heap.
Executing t = s copies those three machine words bitwise from s into t. Because the heap pointer ptr is duplicated verbatim, a single assignment leaves two stack variables pointing to the exact same heap buffer rather than giving each variable its own buffer.
When execution reaches the closing brace }, local variables exit in reverse order of declaration—t first, then s. Our scope-exit rule fires once for each variable:
tleaves scope and automatically frees the heap buffer it points to.sis still in scope, holding aptrthat now points to freed memory—a dangling pointer.- Moments later,
sleaves scope as well and frees that exact same heap address a second time—triggering a double free and undefined behavior.
The failure stems directly from the post-assignment state: whenever two active stack variables manage the same heap block, “free on scope exit” runs twice. That failure forces out a non-negotiable invariant:
At any given moment, each heap allocation can have only one stack variable responsible for freeing it.
Patching the flaw: invalidating the source variable
Section titled “Patching the flaw: invalidating the source variable”A single t = s broke our baseline model. To preserve correctness without adding a garbage collector or deep-copying heap buffers on every assignment, we have to apply a strict rule patch—since two variables cannot share cleanup responsibility, assigning to a new variable must retire the old one:
When a value managing a heap allocation is assigned, transfer cleanup responsibility to the new variable and mark the source variable invalid immediately, forbidding any further use.
With that patch in place, the hole closes: once t = s runs, t is the only valid variable left. At the closing }, t frees the heap buffer once while the invalidated s does nothing, eliminating the double free. Enforcing source-variable invalidation is what keeps this minimal reclamation model sound.
From variable invalidation to move semantics
Section titled “From variable invalidation to move semantics”Mathematically, the patch works. From a programmer’s perspective, however, it creates an awkward mental split.
Look at the two assignments side by side:
b = a // after assignment, a remains validt = s // after assignment, s suddenly becomes invalidBoth lines use the exact same = operator—why does the source variable stay readable in one case and become unusable on the spot in the other?
Framing = as “copy the value first, then conditionally penalize and invalidate the old variable” works against human intuition. In everyday programming, copying leaves two usable values behind; forcing yourself to memorize which types trigger an invalidation penalty makes every assignment feel like a trap.
To align the rule with natural intuition, language design reshapes the mental model. Instead of describing t = s as “copy, then invalidate,” we split = into two familiar ways of handing values across variables:
- Copy semantics: for values like the integer in
b = athat carry no heap cleanup responsibility, assignment duplicates the value—one becomes two,akeeps its copy intact, and both variables remain usable. - Move semantics: for values like the string in
t = stied to exclusive cleanup responsibility, one cannot become two. Assignment moves the value—along with responsibility for freeing it—out ofsand intot. Because the value has moved out ofs,sis now empty; reading fromsagain makes no sense, and at scope exittalone returns the resource.
Reframing mechanical invalidation as move semantics replaces a negative prohibition with a physical intuition: ask whether the value was copied or moved, and it is immediately clear which variable remains usable and who frees the memory. In this simplified model, values without heap allocations copy, whereas values managing heap allocations move.
Under the hood: move is a language semantics; hardware only copies bytes
Section titled “Under the hood: move is a language semantics; hardware only copies bytes”With the intuition of “moving” in place, we need to anchor it back to hardware reality to prevent a widespread misconception: when we say a value moves from s to t, does the CPU physically relocate data and wipe s clean in memory?
No. “Move” is purely a compile-time semantics; hardware memory has no notion of moving bytes.
Physical memory only reads, copies, or overwrites bytes. Separating runtime memory from the compiler’s internal state table reveals how move semantics actually implements source invalidation underneath:
- In physical memory at runtime, the operation is still a bitwise stack copy:
- The
"hello"character buffer on the heap never moves and is never duplicated. - Because the stack frame is reclaimed as a single block when the function returns,
s’s stack slot cannot be freed early on its own, nor does the runtime write any validity flag into memory. - In an unoptimized baseline model, the CPU executes
t = sthe exact same way it executesb = a—by copying the 24-byte control header bitwise froms’s stack slot intot’s, leaving those same 24 bytes sitting untouched ins(and when emitting optimized machine code, the compiler can often elide even that stack copy).
- The
- Invalidation and transfer happen entirely inside the compiler’s compile-time state table:
- While analyzing source code, the compiler maintains a state table tracking whether each variable currently holds a live value and owns cleanup responsibility.
- Upon seeing
t = s, the table markssas uninitialized / moved-from and reassigns cleanup responsibility tot. - If a later line tries to read
s, the compiler checks its table, sees thatsis no longer live, and rejects the program at compile time before an executable is ever produced. - At the closing
}, the compiler consults the same table and emits a heap-free instruction solely for the still-livet, emitting nothing at all fors.
Keeping both layers distinct lets you switch perspectives cleanly: when reasoning about program logic, think in moves to trace where values and cleanup duties flow; when reasoning about performance, remember that a move is at most a bitwise copy of a small stack header plus a compile-time state update, with zero runtime tracking overhead.
What the minimal model solves—and where it stalls
Section titled “What the minimal model solves—and where it stalls”Together, the two rules derived in this section answer the goal posed in The hard triangle:
- Stack variables automatically free their heap allocations at scope exit—requiring neither manual
freecalls nor runtime scanning or reference counting. - Values carrying cleanup responsibility follow move semantics on assignment (marking the source variable invalid and transferring duty at compile time)—guaranteeing a single variable per heap block and ruling out double frees.
Inside a single block, this model is tight and self-contained. Drop it into everyday multi-function code, however, and an immediate obstacle appears: if you pass a string to a helper function solely to print it once, what does move semantics do to the caller’s variable?
Carry that question into the next section.