Stack Values Need a Size Known at Compile Time, Heap Values Do Not
A program keeps values in two regions. The stack is fast and freed automatically when a function returns, but every value on it must have a size known at compile time. The heap holds values whose size is only known at runtime or that must outlive the function, at the cost of a slower allocation. In Rust, ownership frees heap memory for you, without a garbage collector.
Stack and Heap Compared
| Stack | Heap | |
|---|---|---|
| Size of each value | fixed, known at compile time | can be decided at runtime and grow |
| Allocation | push a frame: very fast | ask the allocator: slower |
| Lifetime | ends when the function's frame is popped | as long as an owner holds it |
| Total size | limited (a few MB per thread by default) | limited by available memory |
| Examples in Rust | i32, bool, fixed arrays, the pointer part of a String |
the characters of a String, a Vec's elements, Box<T> contents |
Box Puts a Value on the Heap
let b = Box::new(5); // the 5 lives on the heap, b (a pointer) on the stack
// b goes out of scope here: Rust drops the Box and frees the heap memory
Box<T> is the simplest smart pointer: a pointer that owns its data and frees it when dropped. Rc<T> (shared ownership) and Arc<T> (shared across threads) follow the same idea.
References
- Programming Languages MOC - hub for language notes.
- Rust Variables Are Immutable Unless Declared mut - the bindings that own these values.
- The Rust Programming Language: What Is Ownership? - stack, heap and ownership rules.
- The Rust Programming Language: Using Box<T> - heap allocation with
Box.
Review cards
Flashcard Why must every stack value have a size known at compile time?
A function's stack frame is laid out at compile time and pushed in one step. A value whose size is only known at runtime, or that grows, has to go on the heap.
Flashcard What happens to heap memory when the owner of a `Box<T>` goes out of scope?
Rust automatically drops the Box and frees the heap memory.
Quiz Which statement about the stack and the heap in Rust is true?
- The stack holds values of any size; heap values need a size known at compile time
- In Rust, heap memory must be freed explicitly
- Both need sizes known at compile time
- Heap values can be sized at runtime; stack values need a size known at compile time
Rust frees heap memory when its owner goes out of scope: no free() and no garbage collector.