Stack vs Heap
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 herestack (frame of show) heap
pages: 412
title: ptr ───────────────────▶ I r o n T i d e s
len: 10
capacity: 10On 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.
The shortcut
For any value, ask: "Is its size fixed when the code is compiled?" Yes → it can live wholly on the stack. No → the data goes on the heap, and something on the stack points to it.
The card number
A
u32: always 4 bytes. Stack.
Drills
Answer fast — trust the rule.
Where is the value of let days: i32 = 14; inside a function stored?
For let title = String::from("Iron Tides");, where are the characters themselves?
On a 64-bit machine, how big is the part of a String kept on the stack?
When a function that created a String returns, what frees the heap text?
Remember
- Fixed-size values live on the stack; growable data lives on the heap behind a pointer.
- Ask: "is its size known at compile time?"
- Rust frees heap data when its owner goes out of scope: no leaks, no double frees.
