Sub topic 1
Why ownership exists: stack, heap, and manual memory
Prerequisites
This chapter assumes you know basic Rust syntax (variables, functions, structs, enums) and can build and run a program with cargo. You should also know that the stack and the heap are two regions of memory, and you should have met String, Vec, and &str. No ownership rules are assumed. This chapter explains why they exist.
Two places to keep data
A running program stores values in two main places.
- The stack holds values of a size known at compile time. Each function call pushes a frame, and returning pops it. Allocation and cleanup are automatic and fast.
- The heap holds values whose size is only known at run time, or that must outlive the function that created them. The program asks an allocator for space and gets back a pointer.
A String uses both. The pointer, length, and capacity sit on the stack. The text bytes sit on the heap.
fn main() {
let n: i32 = 42; // stack only
let s = String::from("hello"); // pointer on stack, bytes on heap
println!("{n} {s}");
}The problem with manual memory
Heap memory must be given back exactly once. In C you call malloc and free yourself, and the language does not check your work. Three classic bugs follow.
| Bug | What happens |
|---|---|
| Memory leak | You never call `free`, so memory is lost until the program exits. |
| Double free | You call `free` twice on the same pointer, which corrupts the allocator. |
| Use after free | You read or write through a pointer after `free`, which gives undefined behavior. |
Garbage-collected languages such as Java or Go avoid these bugs by scanning memory at run time. That costs CPU time, memory, and sometimes pauses, and it gives you less control over when cleanup happens.
Rust's answer
Rust gives each heap value one owner, a variable responsible for it. When the owner goes out of scope, Rust frees the value automatically. The compiler checks how values are moved and borrowed, so these checks cost nothing at run time.
This addresses each bug:
- Leaks: cleanup is inserted where the owner goes out of scope.
- Double free: only one owner exists, so only one free happens.
- Use after free: the compiler rejects code that uses a value after its owner has given it up.
The rest of this tutorial covers the rules and tools that make this work: the ownership rules, moves, borrowing, and lifetimes.
Exercise
A String variable s is declared in main. Which parts live on the stack, which on the heap, and why can Rust free the heap part without a garbage collector?
Show answer
The pointer, length, and capacity live on the stack. The text bytes live on the heap. Rust can free the bytes because s is their single owner. When s goes out of scope, the compiler inserts the cleanup, so no run-time scanning is needed.