Stack vs Heap
In this page:
What Lives on the Stack
Fixed-size values known at compile time, like integers, floats, booleans, and chars, are stored on the stack. Stack allocation is extremely fast because it just moves a pointer up or down.
Example: What Lives on the Stack
fn main() {
let a: i32 = 10;
let b: f64 = 3.14;
println!("Stack values: {} and {}", a, b);
}
Login to try C/C++/Java/PHP code in the editor
What Lives on the Heap
Data whose size can grow at runtime, like the contents of a String or Vec, is allocated on the heap. The variable itself holds a small stack-based header pointing to that heap data.
Example: What Lives on the Heap
fn main() {
let mut heap_data = String::from("start");
heap_data.push_str(" grows on the heap");
println!("{}", heap_data);
}
Login to try C/C++/Java/PHP code in the editor
Why the Distinction Matters for Ownership
Ownership rules exist largely to manage heap data safely: when an owning variable is dropped, Rust frees the corresponding heap allocation exactly once, preventing memory leaks and double frees.
Example: Why the Distinction Matters for Ownership
fn main() {
{
let boxed = String::from("owned heap data");
println!("{}", boxed);
} // heap memory freed automatically here
println!("Scope ended, memory reclaimed");
}
Login to try C/C++/Java/PHP code in the editor
Stack Is Faster, Heap Is Flexible
Because the stack only ever grows or shrinks at one end, pushing and popping from it is very cheap. The heap allows flexible, dynamically-sized allocations at the cost of slightly more overhead to allocate and access.
Example: Stack Is Faster, Heap Is Flexible
fn main() {
let stack_value = 42; // fast, fixed size
let heap_value = vec![1, 2, 3, 4]; // flexible, can grow
println!("{} and {:?}", stack_value, heap_value);
}
Login to try C/C++/Java/PHP code in the editor
- Assuming all data in Rust lives on the heap -- fixed-size,
Copyvalues like integers live on the stack. - Thinking
Stringitself lives entirely on the heap -- only its character data does; theStringstruct's pointer, length, and capacity live on the stack. - Believing heap allocation is always slower and should be avoided entirely, when it is simply necessary for data whose size can grow.
- The stack stores fixed-size data quickly, in last-in-first-out order; the heap stores data whose size can grow or is unknown at compile time.
- Types like
StringandVeckeep a small fixed-size header on the stack that points to variable-size data on the heap. - Stack allocation and deallocation is very fast; heap allocation involves more bookkeeping and is comparatively slower.
- Ownership rules apply to both, but they matter most for correctly freeing heap-allocated memory exactly once.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: