Stack vs heap
Locals and fixed-size values live on the stack. Box, Vec, String, and other owning pointers store their payloads on the heap. Rust chooses the heap when the size is dynamic or the value must outlive the frame.
Detailed Explanation
The stack is a per-thread bump allocator: pushing a frame is incrementing a pointer, popping is decrementing. A local i32, a local [u8; 8], a local struct { a: i32, b: i32 } sit there. Their size is known at compile time. When the function returns, they are gone.
The heap is the general allocator (malloc / the system allocator / a custom one). Box::new allocates. Vec allocates when capacity is exceeded. String is a Vec<u8>. The header (pointer, length, capacity) can still live on the stack; the bytes live on the heap. Moving the header is cheap. Cloning the bytes is not.
Rust does not have new as a keyword for every object. You allocate when a type's API does. A struct Session { id: u64 } constructed as a local is on the stack. Put it in a Vec and that element is on the heap (inside the vec's buffer). Put it in a Box and it is on the heap alone.
Stack overflows are real. A huge local array, or a deep recursion, crashes. Heap exhaustion returns (or aborts, depending on the alloc error hook). Prefer Vec for large buffers. Prefer an explicit heap stack (Vec) over deep recursion.
Escape analysis is not a feature you control like in Go. If you return a Session by value, it may be written directly into the caller's slot (copy elision). If you return &Session to a local, it does not compile. Ownership, not an optimiser, decides whether a value can outlive the frame.
When you use the stack: small, fixed, short-lived values. When you use the heap: growable buffers, recursive types, values that many owners share (Rc/Arc), trait objects.
Code Examples
fn main() {
let stack_n = 17; // stack
let heap_n = Box::new(17); // heap int, stack pointer
let heap_buf = vec![1, 2, 3]; // stack header, heap buffer
println!("{stack_n} {} {}", *heap_n, heap_buf.len()); // prints: 17 17 3
}Common Gotchas
A large local array can overflow the stack
`[u8; 1_000_000]` as a local is a crash on a small thread stack. Use `Vec`.
Moving a `Vec` does not copy the heap buffer
Only the header moves. That is the point of owning pointers.
Recursion is stack space
A million-deep DFS should use a `Vec` stack on the heap.
The header location is not the data location
A `String` local is a stack header plus heap bytes. `size_of::<String>()` is three words, not the text length.