Skip to content

1.6 Ownership and borrowing: inserting free at the exact right spot

Across the previous five sections, without writing a single line of real Rust syntax, we followed stack and heap mechanics step by step to derive an automatic memory reclamation model that relies neither on manual free calls nor on a runtime garbage collector.

To close the chapter, we bring out the standard vocabulary from the official Rust documentation and match each term directly to the mechanisms you derived.

Matching the three ownership rules in The Book

Section titled “Matching the three ownership rules in The Book”

Open the ownership chapter of The Rust Programming Language (The Book), and the first thing presented is the three ownership rules:

  1. Each value in Rust has an owner.
  2. There can only be one owner at a time.
  3. When the owner goes out of scope, the value will be dropped.

Memorized in isolation from memory layout, those three lines read like arbitrary restrictions. Matched against our derivation in Copy and move, each rule maps to a concrete physical cause:

  • Rules one and three (who frees memory, and when): a heap buffer does not know when to reclaim itself, whereas the stack variable holding its control header has a deterministic scope exit (}). Naming that stack variable the owner and automatically triggering drop when it leaves {} eliminates manual free calls.
  • Rule two (why only one owner at a time): if t = s left two live variables managing the same heap buffer, leaving {} would trigger a double free. To guarantee single release, assigning a value with cleanup duty transfers both the value and responsibility to the new variable—marking the old variable invalid at compile time while copying only the stack header bitwise at runtime. That transfer is a move; when no heap cleanup duty is involved, bitwise copying leaves both variables usable—a copy.

Matching borrowing, lifetimes, and the borrow checker

Section titled “Matching borrowing, lifetimes, and the borrow checker”

With the three ownership rules alone, even calling a read-only helper print_it(s) moves the argument and frees its heap buffer early. To support everyday function composition without sacrificing pointer safety, References and Dangling references forced out two companion mechanisms:

  • References and borrowing: a restricted pointer that physically stores a target address while stripping away cleanup duty is a reference; creating a reference to let code read through an address without giving up ownership is borrowing (“use the address to read the data; the duty to free it stays with me”).
  • Lifetimes and the borrow checker: because a reference does not control deallocation, an owner leaving scope early would leave the reference dangling. The static analysis pass inside the compiler that tracks variable liveness, blocks use-after-move, and verifies that no reference’s valid span (lifetime) outlives its owner is the borrow checker.

Tracing the chain of “problem encountered → rule derived → Rust terminology” across all five sections condenses the entire chapter into one table:

Problem encountered during derivation Model rule derived Core Rust terminology
Heap allocations stay behind after stack frames return; missed cleanup leaks memory Bind each heap block to a single stack variable and free it automatically at } Ownership / Drop
Copying the header bitwise in t = s frees the same heap block twice Transfer cleanup duty on assignment and mark the source variable invalid Move vs. Copy
Passing by value moves arguments, destroying heap data after a single read Pass an eight-byte stack address stripped of cleanup duty (read-only) Reference / Borrowing
Target variable exits {} early and frees data while an outer reference survives Verify at compile time that a reference’s valid span never outlives its target Lifetime / Borrow checker

Stripping away the jargon: automatic free insertion at compile time

Section titled “Stripping away the jargon: automatic free insertion at compile time”

Encountering “ownership, moves, borrowing, and lifetimes” all at once often gives the impression that Rust runs an elaborate memory-management engine under the hood.

Step back to our starting point in The hard triangle: dynamically allocated heap memory ultimately has to be returned to the allocator through a call equivalent to C’s free. Focusing strictly on heap reclamation in this chapter, strip away every piece of terminology and the entire system performs one job: letting the compiler stand in for the programmer, calculate the single valid release point at compile time, and automatically insert that free call (unified in Rust under drop)—ownership decides which closing } gets the call, move semantics guarantees the same heap block is never freed twice, and borrowing plus lifetimes guarantee no pointer ever reads that block after free runs.

Once the borrow checker verifies the program and bakes those cleanup calls statically into machine code, ownership, borrowing, and lifetimes are completely erased from the compiled binary. At runtime, no collector scans memory and no reference counters tick—execution runs straight through, matching carefully hand-written C.

Design exercise: choosing how to pass a loaded configuration

Section titled “Design exercise: choosing how to pass a loaded configuration”

Before touching real Rust syntax, put this chapter’s model to work on an architectural call.

Suppose a main block loads a configuration string config from disk (storing its character buffer on the heap) and runs three steps in sequence:

  1. Call validate(config) to check whether the format is well-formed (reads config only).
  2. Call print_banner(config) to log a startup summary (reads config only).
  3. Call start_server(config) to hand the configuration over to a long-running background server; the main block never uses config afterward.

Use our model to answer three questions:

  1. Choose how each argument is passed: across validate, print_banner, and start_server, which calls should pass a reference (&config), and which should pass by value (config, triggering a move)? Why?
  2. Diagnose a faulty return: suppose whoever implements validate builds a temporary local string temp inside the function and tries to return a reference &temp to the caller. Which rule causes the borrow checker to reject the code, and what physical fact does it violate?
  3. Locate the final release point: under your answer to question one, at which closing brace } is the heap buffer behind config ultimately freed?
Check the derivation
  1. Argument-passing choices:
    • validate(&config) and print_banner(&config) should pass references (borrows). Both functions only inspect the text, and the main block still needs config after each call returns; passing by value would move config into validate, invalidate it in the caller, and free the heap buffer as soon as validate returned.
    • start_server(config) should pass by value (move). The main block has no further use for config, whereas the server needs to take exclusive ownership—and subsequent cleanup responsibility—for that heap buffer.
  2. Faulty return diagnosis:
    • The borrow checker rejects &temp under the lifetime rule.
    • Physical fact: temp lives inside validate’s stack frame. When validate hits } and returns, temp leaves scope, frees its heap buffer on the spot, and its stack frame is reclaimed. Returning &temp to the caller extends the reference’s valid span past its owner’s live span, producing a guaranteed dangling reference.
  3. Final release point:
    • Because the first two calls borrow config without transferring cleanup duty and the third call start_server(config) moves ownership into start_server’s parameter (or into a server field that takes it over), the heap buffer is freed at the closing } where whichever owner inside start_server holds it finally leaves scope.

Next step: open the compiler and test real code

Section titled “Next step: open the compiler and test real code”

This chapter built the core backbone of single ownership plus read-only borrowing (mutating data through references and sharing ownership across multiple holders will be derived later from the exact same physical principles when real workloads require them).

In the next chapter, we open the compiler and bring this model into real Rust code—writing our first let, mut, and = statements to watch how the compiler adjudicates variable declarations, reassignment, and shadowing.

Next chapter: Variables and assignment →