Sub topic 8
Length, capacity and reallocation
This chapter explains how a Vec<T> manages its memory. It assumes you can create a Vec, push to it, and read the basics of ownership and borrowing. You should also know how to run a program with cargo.
Length and capacity are different numbers
A Vec<T> stores its elements in one contiguous block of heap memory. It tracks three things internally: a pointer to that block, the number of elements currently stored (the length), and the number of elements the block can hold (the capacity).
len()returns how many elements the vector holds right now.capacity()returns how many elements it can hold before it must get a bigger block.capacity() >= len()always holds.
Only the first len() slots contain valid values. The remaining slots are reserved but uninitialized, and safe Rust never lets you read them.
fn main() {
let mut v: Vec<i32> = Vec::new();
println!("len = {}, capacity = {}", v.len(), v.capacity());
for i in 0..10 {
v.push(i);
println!("len = {}, capacity = {}", v.len(), v.capacity());
}
}A new empty Vec has capacity 0 and allocates nothing. On the first push it allocates. After that, each time the length would exceed the capacity, the vector allocates a larger block, copies (moves) the elements over, and frees the old block. This is called reallocation.
How growth works
The standard library grows the capacity geometrically. When a push needs more room, the new capacity is at least double the old one. For small element types, the first allocation is usually 4 slots (8 for 1-byte elements, 1 for very large elements).
On current stable compilers, the program above typically prints capacities 4, 4, 4, 4, 8, 8, 8, 8, 16, 16. Treat these numbers as an implementation detail. The language documents only that capacity is at least the length and that growth is amortized. Do not write code that depends on the exact values.
Doubling matters because it keeps push cheap on average. A single push that triggers reallocation costs time proportional to the current length, because every element is moved. But reallocations get rarer as the vector grows. Spread over many pushes, the cost per push is constant. This is called amortized O(1).
Reserving space up front
If you know roughly how many elements you will add, ask for the space once. Vec::with_capacity(n) creates an empty vector whose capacity is at least n. The length is still 0.
fn main() {
let mut v: Vec<u32> = Vec::with_capacity(10);
assert!(v.capacity() >= 10);
assert_eq!(v.len(), 0);
for i in 0..10 {
v.push(i);
}
// No reallocation happened: capacity was reserved up front.
println!("len = {}", v.len()); // len = 10
}The assertion uses >= because the documentation guarantees "at least" n. In practice the allocator may give you more, and for zero-sized types such as (), the capacity is reported as usize::MAX.
Related methods:
| Method | Effect |
|---|---|
| `Vec::with_capacity(n)` | New empty vector with room for at least `n` elements |
| `reserve(extra)` | Ensures room for at least `len + extra` elements. May over-allocate to keep growth geometric |
| `reserve_exact(extra)` | Asks for exactly `len + extra`, but the allocator may still give more |
| `shrink_to_fit()` | Asks to drop spare capacity down to the length |
| `shrink_to(min)` | Shrinks capacity but keeps at least `min` |
| `clear()` | Sets length to 0 and drops the elements. Capacity is unchanged |
| `truncate(n)` | Drops elements past index `n`. Capacity is unchanged |
Use reserve when you append in batches, for example before extending a vector from an iterator with a known size. Use reserve_exact only when you know no further growth will happen, since repeated reserve_exact calls can cause a reallocation each time.
Removing elements does not release memory
A common surprise is that capacity never shrinks on its own.
fn main() {
let mut v: Vec<u8> = (0..1000).map(|n| (n % 256) as u8).collect();
println!("before: len = {}, cap >= 1000: {}", v.len(), v.capacity() >= 1000);
v.clear();
println!("after clear: len = {}, cap >= 1000: {}", v.len(), v.capacity() >= 1000);
v.shrink_to_fit();
println!("after shrink: len = {}, cap = {}", v.len(), v.capacity());
}After clear, the length is 0 but the thousand-slot block is still owned by the vector. That is useful: you can reuse a buffer in a loop without allocating each time. It is a cost if a huge vector becomes small and lives for a long time. In that case call shrink_to_fit, which reallocates to a smaller block (or frees it entirely when the length is 0).
Reallocation and references
When a vector reallocates, its elements move to a new address. Any reference that pointed into the old block would then dangle. This is the underlying reason that Rust refuses to compile code that holds a reference into a Vec while calling push: the push might reallocate. The previous chapter on borrowing covers the compiler error. What matters here is that the rule holds even when capacity is large enough that no reallocation would actually happen. The borrow checker reasons about types and lifetimes, not about runtime capacity.
fn main() {
let mut v = Vec::with_capacity(100);
v.push(1);
// Compiles: the reference is not used after push.
let first = &v[0];
println!("{first}");
v.push(2);
println!("{:?}", v);
}The same code with println!("{first}") moved after v.push(2) would be rejected, even though capacity 100 means no move can occur.
Raw pointers are different. If you take a pointer with as_ptr() and use it in unsafe code, you must make sure no operation that might reallocate happens while the pointer is in use. Safe Rust prevents this for you.
Capacity and element moves
Reallocation moves elements with a bitwise copy, and Rust does not call any user code during the move. There is no copy constructor. For a Vec<String>, only the three-word String headers (pointer, length, capacity) are copied. The text each String points to stays where it is. So growing a Vec<String> is cheaper than the memory footprint of its contents suggests.
Reallocation can still be costly for large vectors of large element types. A Vec<[u8; 4096]> moves 4 KiB per element. If you know the final size, with_capacity removes that cost.
Capacity overflow and allocation failure
A Vec cannot hold more than isize::MAX bytes. Requests beyond that panic with "capacity overflow". If the allocator cannot satisfy a request, the default behavior is to abort the process. When you need to handle that case, such as when sizes come from untrusted input, use try_reserve, which returns a Result instead.
use std::collections::TryReserveError;
fn build_buffer(size: usize) -> Result<Vec<u8>, TryReserveError> {
let mut buf = Vec::new();
buf.try_reserve(size)?;
buf.resize(size, 0);
Ok(buf)
}
fn main() {
match build_buffer(1024) {
Ok(buf) => println!("allocated {} bytes", buf.len()),
Err(e) => println!("allocation failed: {e}"),
}
match build_buffer(usize::MAX) {
Ok(_) => println!("unexpected success"),
Err(e) => println!("allocation failed: {e}"),
}
}The second call fails with a TryReserveError rather than a panic or abort.
Common mistakes
- Using
capacityas a length.Vec::with_capacity(10)gives you an empty vector. Indexingv[0]on it panics. Usevec![0; 10]orresizeif you want ten elements. - Asserting exact capacity. Tests that check
capacity() == 8break when the standard library changes its growth policy. Check>=instead. - Calling
shrink_to_fitin a loop. Each call may reallocate, and the next push will grow the vector again. Shrink once, after the vector reaches its final size. - Expecting
clearto free memory. It drops the elements only. - Premature reservation. For small vectors, the default growth is fast enough. Reserve when you have a known size and the vector is large or the code is hot, and measure when in doubt.
Why this matters for the rest of the tutorial
HashMap has the same two numbers, with the same distinction. A map has a length and a capacity, HashMap::with_capacity(n) exists, and growth rehashes entries into a larger table. The mechanics differ, but the reasoning carries over. The final chapter on choosing a collection uses this idea when comparing costs.
Exercise
You build a Vec<u64> with Vec::with_capacity(50), push 20 elements, then call clear(). What are len() and capacity() afterward, and what would you call to give the memory back?
Show answer
len() is 0 and capacity() is still at least 50, because clear drops the elements but keeps the allocation. Call shrink_to_fit() (or shrink_to(n) to keep some room) to release the spare memory.
Exercise
A loop pushes 1,000,000 integers into a Vec::new(). The final size is known in advance. Why does Vec::with_capacity(1_000_000) help, and does it change the amortized cost per push?
Show answer
With with_capacity, the vector allocates once, so there are no intermediate reallocations or element moves. The amortized cost per push was already constant with geometric growth, so the big-O does not change. The gain is a smaller constant factor and less peak memory churn.
Exercise
A vector has capacity 100 and length 1. Why does the compiler still reject code that holds &v[0] across a call to v.push(2)?
Show answer
The borrow checker works from types and lifetimes, not runtime values. push takes &mut self and might reallocate in general, so it cannot be called while a shared reference into the vector is still in use.