Sub topic 1
Where allocations come from: stack, heap and the allocator
Prerequisites
This chapter assumes you know Rust ownership, borrowing and lifetimes. It also assumes you have used Vec, String and Box, and can run cargo build and cargo test. You do not need any knowledge of allocator internals.
Two places to store data
A running Rust program keeps values in two main places.
- The stack is a region of memory that grows and shrinks with function calls. Each call gets a frame. Reserving space for a local variable only moves a pointer, so it costs almost nothing. The compiler must know the size of every stack value at compile time.
- The heap is a pool of memory that the program requests at run time. A value can have any size and can outlive the function that created it. Each request goes through an allocator, which finds a free block, records it, and later takes it back.
An allocation is one request to the heap. It costs more than a stack write because the allocator does bookkeeping, may lock shared state, and may ask the operating system for more memory. The returned memory is also often cold in the CPU cache. One allocation is cheap. Millions of them in a hot loop are not.
Which types allocate
Many Rust types are small fixed-size handles on the stack that point to data on the heap.
| Type | Handle on the stack | Data on the heap |
|---|---|---|
| `i32`, `f64`, `[u8; 16]`, plain structs | The whole value | None |
| `&str`, `&[T]` | Pointer and length | None (borrows existing data) |
| `Vec<T>` | Pointer, capacity, length | The elements |
| `String` | Pointer, capacity, length | The UTF-8 bytes |
| `Box<T>` | Pointer | One `T` |
| `Rc<T>`, `Arc<T>` | Pointer | `T` plus reference counts |
An empty Vec::new() or String::new() does not allocate. The first push or insert does. A zero-sized type in a Box does not allocate either.
The allocator
Rust programs call a global allocator whenever a heap type needs memory. By default this is the system allocator, such as malloc on Linux. The standard library talks to it through the GlobalAlloc trait, which has alloc and dealloc methods. Every Vec growth, String creation and Box::new ends in one of these calls.
Dropping a value calls dealloc. This happens automatically at the end of scope, so allocation cost is easy to forget. You never write free, but the cost is still there.
A worked example
Compare these two functions.
struct Point {
x: f64,
y: f64,
}
fn on_stack() -> f64 {
let p = Point { x: 1.0, y: 2.0 };
p.x + p.y
}
fn on_heap() -> f64 {
let p = Box::new(Point { x: 1.0, y: 2.0 });
p.x + p.y
}
fn main() {
println!("{} {}", on_stack(), on_heap());
}Both return 3.0. The first uses only stack space. The second makes one allocation and one deallocation for a value that never needed the heap. The optimizer can sometimes remove such a Box, but you should not rely on it.
Why reducing allocations helps
- Each allocation and deallocation costs time.
- Many small allocations fragment memory and scatter data, which hurts cache use.
- Shared allocators can contend on locks under heavy multithreading, although modern allocators reduce this.
Fewer allocations do not always mean faster code. A clearer design with a few allocations is often the right choice. The next chapter shows how to count allocations, so you can decide with evidence instead of guessing.
Exercise
A function builds a String with String::new() and returns it without pushing anything. How many heap allocations happen, and which part of the String lives on the stack?
Show answer
Zero allocations happen, because an empty String has no heap buffer yet. The stack holds the handle: a pointer, a capacity of 0, and a length of 0. The first push would trigger the first allocation.