Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Concepts

The stack and the heap in Rust

Reference for where Rust values live: stack frames, heap allocations with Box, Vec and String, static memory, value sizes, fat pointers and stack overflow.

Rust programs keep data in three places. The stack holds local variables and function arguments in one frame per call; allocation is just moving a pointer, and the frame disappears when the function returns. The heap holds data whose size is only known at run time or that must outlive a single call; it is requested from the allocator and freed when its owner is dropped. Static memory (read-only or global data baked into the executable) holds string literals and static items for the entire run.

Rust decides placement from types. A value's size must be known at compile time to live on the stack (it must be Sized). Types such as Box<T>, Vec<T> and String keep a small, fixed-size handle on the stack that points at a heap buffer. Moving such a value copies the handle only.

Rust
let n = 5;                  // i32 on the stack
let b = Box::new(5);        // pointer on the stack, i32 on the heap
let v = vec![1, 2, 3];      // (pointer, capacity, length) on the stack, items on the heap
let s = "literal";          // (pointer, length) on the stack, text in static memory

Try it

Rust Sizes of the stack part

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Moving a Box moves only the pointer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Recursion uses stack frames

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

How placement works

Stack

Locals, function arguments, return addresses and temporaries live in the current call's frame. Allocation and release are almost free and the memory is cache-friendly. The stack is limited: the main thread usually gets a few megabytes (8 MiB on Linux by default, 1 MiB on Windows), spawned threads 2 MiB unless you configure thread::Builder::stack_size. Exceeding it aborts the process with a stack overflow, which is not a panic and cannot be caught.

Heap

Data goes on the heap through an allocator, via Box::new, Vec, String, Rc, Arc, HashMap and so on. Allocation costs a call into the allocator (tens of nanoseconds, more under contention) and each allocation is freed exactly once, when its owner drops. You choose the allocator with #[global_allocator].

Static memory

String literals have type &'static str and live in the binary. A static item has a fixed address for the whole run, and a const is inlined wherever it is used. See static.

Fat pointers

A reference or Box to a dynamically sized type carries extra data. &str and &[T] hold a pointer and a length (16 bytes on 64-bit targets), and &dyn Trait or Box<dyn Trait> hold a pointer and a vtable pointer (also 16 bytes).

Usage notes

  • "Box it" to shrink or break recursion. A recursive type such as a linked list node needs Box<Node> so its size is finite. Boxing a large value also makes moves cheaper, though moves of big arrays are often optimized away.
  • Niche optimization: Option<Box<T>>, Option<&T> and Option<NonZeroU32> take no extra space because the null (or zero) bit pattern represents None, as the first example prints.
  • Vec::with_capacity avoids repeated reallocation when you know the size roughly. Capacity growth beyond what you request is an implementation detail.
  • Stack versus heap is not speed alone. Heap allocation enables dynamic size and longer life; stack allocation is cheaper but limited to scope and size.
  • Large arrays: let a = [0u8; 10_000_000]; in a function can overflow the stack. Use vec![0; n] or Box<[u8]>.
  • Layout details (field order, padding) are unspecified without #[repr(C)]; see repr.
  • Do not guess addresses. They change between runs, and pointer comparison is only meaningful for identity checks like the one above.