Sub topic 17
Where Tuples and Arrays Live in Memory
This chapter assumes you can read basic Rust and know how tuples, arrays, slices and Vec behave. It also assumes you know what & references do. Here you will see how those types sit in memory, what that costs, and where the guarantees stop.
Inline storage on the stack
A tuple or an array stores its elements inline, inside the value itself. There is no pointer to a separate allocation. If a local variable holds a [u32; 5], the 20 bytes of data are in that function's stack frame.
This is the main difference from Vec<T>. A Vec stores three words on the stack (pointer, capacity, length), and the elements live in a heap buffer.
Arrays: contiguous and exactly sized
An array [T; N] takes exactly N * size_of::<T>() bytes. The language guarantees this, with no header and no padding between elements. Element i sits at the start of the array plus i * size_of::<T>().
use std::mem::size_of;
fn main() {
println!("{}", size_of::<[u32; 5]>()); // 20
println!("{}", size_of::<[u8; 0]>()); // 0
let a = [10u32, 20, 30];
let p0 = &a[0] as *const u32 as usize;
let p1 = &a[1] as *const u32 as usize;
let p2 = &a[2] as *const u32 as usize;
println!("{} {}", p1 - p0, p2 - p1); // 4 4
}Because the layout is contiguous, &a[1..3] is cheap. It needs no copy, only a pointer to element 1 and a length of 2.
Tuples: layout is not specified
A tuple holds its fields inline, but Rust does not promise their order in memory. The compiler may reorder fields to reduce padding. Padding is the unused bytes that keep each field aligned to its type's requirement.
Compare a tuple with a #[repr(C)] struct, which fixes C's layout rules: fields in declaration order, with padding.
use std::mem::{align_of, size_of};
#[repr(C)]
struct CLayout {
a: u8,
b: u32,
c: u8,
}
fn main() {
// repr(C): 1 byte + 3 padding + 4 bytes + 1 byte + 3 padding = 12
println!("repr(C): {}", size_of::<CLayout>());
// Default Rust layout: the compiler may place the u32 first.
// Typically prints 8, but the language does not promise it.
println!("tuple: {}", size_of::<(u8, u32, u8)>());
println!("align of (u8, u32): {}", align_of::<(u8, u32)>());
}A tuple's size is always a multiple of its alignment, which is the largest alignment among its fields. For (u8, u32, u8) the minimum possible size is therefore 8, because the six bytes of data round up to a multiple of 4.
Arrays differ from tuples here. Since every element has the same type, there is nothing to reorder, so the layout is fully defined.
Zero-sized values
Some of these types take no space at all:
| Type | `size_of` |
|---|---|
| `()` | 0 |
| `[u8; 0]` | 0 |
| `[(); 1000]` | 0 |
| `((), ())` | 0 |
A one-element tuple (T,) has the same size as T. The compiler handles zero-sized types without generating any storage, so Vec<()> never allocates for its elements.
Copies, moves, and large values
An array or tuple is Copy when all its elements are Copy. Passing or assigning one by value then copies every byte. For [i32; 4] that is trivial. For [u8; 1_000_000] it is a real memcpy each time.
fn sum_by_value(data: [u64; 1024]) -> u64 {
data.iter().sum() // the caller's 8 KiB was copied in
}
fn sum_by_ref(data: &[u64]) -> u64 {
data.iter().sum() // only a pointer and a length were passed
}
fn main() {
let data = [1u64; 1024];
println!("{}", sum_by_value(data));
println!("{}", sum_by_ref(&data));
println!("{}", data.len()); // still usable: [u64; 1024] is Copy
}The optimizer can often remove such copies, but you should not rely on it. Take &[T] for read access, as the slices chapter recommends.
Stack limits
Stack space is small and fixed. The main thread on Linux commonly gets 8 MiB. Threads created with std::thread::spawn get 2 MiB by default. An array larger than the remaining stack aborts the program with a stack overflow, and no error is returned that you can handle.
For large fixed-size data, move it to the heap. A boxed slice is a heap buffer that cannot grow, with no capacity field.
fn main() {
// 100 MB on the heap. Writing [0u8; 100_000_000] as a local would risk overflow.
let big: Box<[u8]> = vec![0u8; 100_000_000].into_boxed_slice();
println!("{}", big.len());
println!("{}", big[99_999_999]);
}Slice references are fat pointers
A reference to an array, &[T; N], is one pointer, because the length is in the type. A slice reference &[T] has no length in its type, so it carries the length at run time. It is a "fat pointer" of two words: an address and a count.
use std::mem::size_of;
fn main() {
let word = size_of::<usize>();
println!("{}", size_of::<&[i32; 4]>() == word); // true
println!("{}", size_of::<&[i32]>() == 2 * word); // true
println!("{}", size_of::<Vec<i32>>() == 3 * word); // true in practice
}The first two comparisons hold on any platform. The Vec one reflects the current standard library implementation, which is not a documented guarantee.
This is why bounds checks work on slices. The length is available at run time to compare against the index. For arrays the length is known at compile time, so a constant index out of range can be rejected during compilation, and the compiler can often prove a loop index is in range and drop the check.
Summary of the costs
| Type | Where the data lives | Handle size | Length known |
|---|---|---|---|
| `(A, B)` | Inline | Size of the fields plus padding | Compile time |
| `[T; N]` | Inline | `N * size_of::<T>()` | Compile time |
| `&[T]` | Elsewhere | 2 words | Run time |
| `Vec<T>` | Heap | 3 words | Run time |
Exercise
A function takes grid: [[f64; 512]; 512] by value and is called inside a thread started with std::thread::spawn. The program crashes with a stack overflow. Why does it crash, and what are two ways to fix it?
Show answer
The array holds 512 512 8 = 2,097,152 bytes (2 MiB), which alone fills a spawned thread's default 2 MiB stack. The call also copies it, so the caller and callee frames both need space. Fix it by changing the parameter to &[[f64; 512]; 512] or &[[f64; 512]] so only a pointer is passed. Also store the data on the heap, for example as a Vec<f64> or Box<[f64]> of 512 * 512 elements. A larger thread stack via std::thread::Builder::stack_size also works but only postpones the limit.