Skip to the workspace
Pebellslearn by building
Ownership and Borrowing  ›  Lesson

Stack vs Heap

Deep Dive: Stack vs Heap 12 minStack and heap describe storage strategies. Values can be stored directly or behind pointers; an owned String typically manages a heap buffer, while its handle can itself live in several kinds of storage.

rust / Stack vs Heap

Explore each scene at your own pace.

01 · The rule

The rule

Stack vs Heap

Stack and heap describe storage strategies. Values can be stored directly or behind pointers; an owned String typically manages a heap buffer, while its handle can itself live in several kinds of storage.

Separate a value's storage location from the ownership rules that control it.

Ownership, the idea at the centre of Rust, is really about one question: who cleans up memory, and when? To answer it you need a picture of the two places a program keeps its data. Once you can see them, the ownership rules in the next lesson will feel obvious.

The rule

Known size goes on the stack; growable data goes on the heap, behind a pointer.

The stack is a pile of frames, one per function call. A frame holds that call's local values, and every value in it has a size known at compile time: an i32 is 4 bytes, a bool 1, a [u32; 7] 28. Pushing a frame on a call and popping it on return is extremely fast, and everything in the frame disappears together.

The heap is a large pool for data whose size is not known in advance or that must be able to grow. The program asks the allocator for a block, gets back its address, and must eventually give the block back. Asking and returning costs more than using the stack, and reaching the data means following a pointer.

A String uses both:

fn show() {
    let pages: u32 = 412;                        // 4 bytes, on the stack
    let title = String::from("Iron Tides");      // see below
}   // frame popped; title's heap text is freed here
stack (frame of show)              heap
pages: 412
title: ptr ───────────────────▶  I r o n   T i d e s
       len: 10
       capacity: 10

On a 64-bit machine the String record on the stack is 24 bytes (pointer, length, capacity, 8 bytes each). The text itself is on the heap. Vec and HashMap follow the same pattern.

In C, forgetting to free that heap block leaks memory, and freeing it twice corrupts the program. Rust ties the heap block to the variable that owns it: when title goes out of scope, Rust frees the text for you, exactly once.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.