Lecture 18 - The heap: allocation, and why it is slower
Announcements
How much room for a name?
Your program is going to ask the user for their name and store it.
How many bytes should the compiler set aside?
You cannot know. Not "it is hard to know". The compiler runs before the user is even at the keyboard.
Yesterday we said the stack works because every size is known at compile time. So the name cannot go on the stack. Today: where it goes instead.
Where we left off
The stack is fast, ordered, and automatic, and it is all three for one reason: every size is known at compile time.
Which leaves an obvious problem. String and Vec can grow. So how have they been working this whole time?
Learning Objectives
By the end of today, you should be able to:
- Explain why dynamically sized data cannot live on the stack
- Name the three parts of a
Stringand say which part is on the heap - Compare the stack and the heap on speed, size, and cleanup
- Draw the stack and the heap at a given point in a program, with types labeled
- Explain why adding up a
Vec<Vec<i32>>by rows is faster than by columns
A demo that should not work
fn main() { let x1: i8 = 10; let mut s1: String = String::from("hello"); let x2: i8 = 20; println!("address of s1 {:p}, size of s1 {}", &s1, size_of::<String>()); println!("{s1}"); s1.push_str(" everyone!"); println!("address of s1 {:p}, size of s1 {}", &s1, size_of::<String>()); println!("{s1}"); }
Look at the output.
- The string got longer. It prints
hello everyone! - The address of
s1did not change - The size of
s1did not change. Still 24 bytes
How can the string be longer if s1 is the same size, in the same place?
Because s1 is not the string.
What a String actually is
Three fields, 24 bytes total, sitting on the stack:
ptr, 8 bytes: the address where the characters arelen, 8 bytes: how many characters there are right nowcap, 8 bytes: how many there is room for
Stack: Heap:
┌─────────────┐ ┌─────┬─────┬─────┬─────┬─────┐
│ s1: String │ │ 'h' │ 'e' │ 'l' │ 'l' │ 'o' │
│ ├ ptr ──────┼─────────▶│ │ │ │ │ │
│ ├ len: 5 │ └─────┴─────┴─────┴─────┴─────┘
│ └ cap: 5 │
└─────────────┘
The characters are somewhere else entirely. push_str changed len, and changed what is at the far end of that arrow. It never touched the 24 bytes on the stack.
This is the shape of every growable type in Rust. Vec, HashMap, HashSet: a small fixed-size handle on the stack, pointing at data that can change size somewhere else.
The heap - library analogy
- The card is on the stack: small, every card the same size, and it tells you where to go
- The book is on the heap: any size, shelved wherever there was room
Yes, librarians call the shelves "the stacks." In this picture they are the heap. Sorry.
If a storage unit works better for you: the key in your pocket is on the stack, the unit across town is the heap.
Remember Customer?
#![allow(unused)] fn main() { enum State { NY, MA, CA } struct Customer { name: String, age: u32, state: State, member: bool, } let alice = Customer { name: "Alice Smith".to_string(), age: 25, state: State::NY, member: true, }; }
Customer in memory
Stack: Heap:
┌────────────────────────┐ ┌───────────────┐
│ alice: Customer │ ┌──▶│ "Alice Smith" │
│ ├ name: String │ │ └───────────────┘
│ │ ptr ───────────────┼──────┘
│ │ len: 11 │
│ │ cap: 11 │
│ ├ age: u32 = 25 │
│ ├ state: State = NY │
│ └ member: bool = true │
└────────────────────────┘
The struct is a fixed size, so it sits on the stack. name is a handle, pointing at its text on the heap. age, state, and member are a fixed size, so they sit right in the struct.
An enum is a fixed size too. Rust stores which variant it is as a small number, NY as 0, MA as 1, CA as 2. One byte, on the stack.
Who cleans up the heap?
- The stack cleans itself up: a frame goes away when the function returns, automatically, with no code.
- The heap does not. Somebody has to say "I am done with this, take it back."
Who does it?
- In C, that somebody is you, and forgetting is a bug.
- In Python, a garbage collector figures it out at run time.
- In Rust, it is the compiler, using a set of rules.
That set of rules is called ownership, and it is the next two weeks.
Stack vs. Heap
| Stack 🍽️ | Heap 📦 |
|---|---|
| Fixed size, known at compile time | Variable size, can grow/shrink |
| Super fast access | Slower access (follow pointer) |
| Automatic cleanup | Manual management needed |
| Limited space | Lots of space |
i32, bool, arrays, tuples | String, Vec, HashMap, etc. |
Don't memorize this table. Every row follows from "the stack keeps things in order and the heap does not." Reason it out, then check yourself against the table.
Think-pair-share: stack or heap?
Your program has to store each of these. Is it small and a fixed size, or could it grow or be big? Write S or H next to each.
- A person's zip code
- A person's street address
- A website's URL
- The barcode on a cereal box
- Whether it is raining right now
- A playlist
- The temperature outside
- A photo from your phone
- A post, capped at 280 characters
- A US state
Stack: 1, 4, 5, 7, 10. Heap: 2, 3, 6, 8. Either: 9. But there's also some subjectivity here.
Why is the heap slower? Remember this?
From Lecture 9: two ways to add up every number in a 10,000 by 10,000 grid.
// Across each row, then down to the next row
for r in 0..rows {
for c in 0..cols {
sum = sum + matrix[r][c];
}
}
// Down each column, then over to the next column
for c in 0..cols {
for r in 0..rows {
sum = sum + matrix[r][c];
}
}
Same 100 million additions. Same Big O. Going down the columns is about 6x slower.
What a Vec<Vec<i32>> looks like
matrix is a Vec of rows, and every row is its own Vec.
Stack: Heap:
┌─────────────────────┐ ┌────────────────┐ ┌───┬───┬───┐
│ grid: Vec<Vec<i32>> │ ┌─▶│ ptr ───────────┼───────▶│ 1 │ 2 │ 3 │
│ ptr ──────────────┼───┘ │ len: 3, cap: 3 │ └───┴───┴───┘
│ len: 3 │ ├────────────────┤ ┌───┬───┬───┐
│ cap: 3 │ │ ptr ───────────┼───────▶│ 4 │ 5 │ 6 │
└─────────────────────┘ │ len: 3, cap: 3 │ └───┴───┴───┘
├────────────────┤ ┌───┬───┬───┐
│ ptr ───────────┼───────▶│ 7 │ 8 │ 9 │
│ len: 3, cap: 3 │ └───┴───┴───┘
└────────────────┘
Each row is its own block on the heap, wherever there was room. Nothing says row 1 comes right after row 0.
Let's check
fn main() { let grid: Vec<Vec<i32>> = vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]]; println!("grid[0][0] {:p}", &grid[0][0]); println!("grid[0][1] {:p}", &grid[0][1]); println!("grid[0][2] {:p}", &grid[0][2]); println!("grid[1][0] {:p}", &grid[1][0]); println!("grid[2][0] {:p}", &grid[2][0]); }
Across a row, the addresses go up by 4, one i32 at a time. The next row starts somewhere else entirely.
The CPU reads memory in chunks
Going out to RAM is slow, compared to everything else the CPU does. So when it needs one number, it does not fetch one number. It fetches the whole chunk around it, 64 bytes on most chips and 128 on my laptop, and keeps it in a small, very fast memory on the chip called the cache.
The library version: you walk to the stacks for one book, and can easily see the whole shelf.
If the next thing you need is on that shelf, it is nearly free.
Across vs. down
Across a row: one trip [ # # # # # # # # ... ] use all of it
Down a column: one trip [ # . . . . . . . ... ] use one number
one trip [ # . . . . . . . ... ] use one number
one trip [ # . . . . . . . ... ] use one number
# is a number you use. Across a row, the next number is a neighbor, already in the chunk. Down a column, every step is a different row, so a different block, so another trip, and you use one number out of each chunk.
So why is the heap slower?
- Getting space is slower. The stack adds to the top. The heap has to hunt for a gap big enough
- Reading it can be slower. Data spread across many blocks means many trips
Activity 18, Problem 1: an array, a Vec, and a String
See Problem 1 on Activity 18.
Stack: Heap:
┌────────────────────────────┐
│ main │
│ a: [i32; 3] = [1, 2, 3] │
│ v: Vec<i32> │ ┌───┬───┬───┐
│ ptr ───────────────────┼───────▶│ 1 │ 2 │ 3 │
│ len: 3, cap: 3 │ └───┴───┴───┘
│ s: String │ ┌─────┬─────┐
│ ptr ───────────────────┼───────▶│ 'h' │ 'i' │
│ len: 2, cap: 2 │ └─────┴─────┘
└────────────────────────────┘
a and v print the same thing but live in different places. An array's size is part of its type, so it fits in the frame. A Vec can grow, so its values go on the heap.
String vs &str - Finally Explained!
We can explain this a bit more now with stack/heap:
String: Owned Text on the Heap
#![allow(unused)] fn main() { let name = "Alice".to_string(); // or String::from("Alice") }
What happens in memory:
Stack: Heap:
┌──────────────┐ ┌─────┬─────┬─────┬─────┬─────┐
│ name: String │ │ 'A' │ 'l' │ 'i' │ 'c' │ 'e' │
│ ├ ptr ───────┼────────▶│ │ │ │ │ │
│ ├ len: 5 │ └─────┴─────┴─────┴─────┴─────┘
│ └ cap: 5 │
└──────────────┘
- String = the metadata on the stack (pointer, length, capacity)
- Actual text = lives on the heap
- You own it = you can modify it, and Rust will clean it up for you
&str: Borrowed Text (Points to Existing Data)
#![allow(unused)] fn main() { let greeting = "Hello"; // This is &str }
What happens in memory:
Stack: (Heap) Program Binary (Text Section):
┌────────────────┐ ┌─────┬─────┬─────┬─────┬─────┐
│ greeting: &str │ │ 'H' │ 'e' │ 'l' │ 'l' │ 'o' │
│ ├ ptr ─────────┼───────────────────────────▶│ │ │ │ │ │
│ └ len: 5 │ └─────┴─────┴─────┴─────┴─────┘
└────────────────┘
- &str = just a pointer and length on the stack
- Actual text = lives in your compiled program
- You're borrowing it = you can read it, but you can't edit it
Two fields, not three. There is no cap because a &str can't grow, it's fixed-size. In a sense, its cap is always its len, which would be redundant to track separately.
Activity 18, Problem 2: a String and a string literal
See Problem 2 on Activity 18.
Stack:
┌──────────────────────────┐
│ print_label │ Program binary:
│ label: &str │ ┌─────┬─────┬─────┐
│ ptr ─────────────────┼───────▶│ 'A' │ 'g' │ 'e' │
│ len: 3 │ └─────┴─────┴─────┘
│ value: i32 = 5 │
└──────────────────────────┘
┌──────────────────────────┐
│ main │ Heap:
│ name: String │ ┌─────┬─────┬─────┐
│ ptr ─────────────────┼───────▶│ 'B' │ 'o' │ 'b' │
│ len: 3, cap: 3 │ └─────┴─────┴─────┘
│ age: i32 = 5 │
└──────────────────────────┘
The String's text is on the heap because it could grow. The literal "Age" was written into the program when it was compiled, so label points into the program itself.
Let's Watch the Stack in Action!
Here's an example showing how the stack builds up and comes down as functions are called.
The diagrams will be online after class but there's space on your paper to draw them yourselves as we go.
fn main() { let x = 42; // Stack variable let name = "Alice"; // Points into the program let result = process_data(x, name); println!("{}", result); } fn process_data(num: i32, text: &str) -> String { let mut doubled = num * 2; // Stack variable // A bracketed scope creates its own mini-stack frame! { let temp_multiplier = 10; // New scope variable let temp_result = doubled * temp_multiplier; // Another scope variable println!("Temp calculation: {}", temp_result); doubled = doubled + 1; // Modify outer variable } // temp_multiplier and temp_result are destroyed here! let greeting = format!("Hello {}, your number is {}", text, doubled); greeting // Return String (heap data) }
Steps 1 to 4. Draw it once, then keep updating it as we go: add each frame when it is called, cross it out when it is gone.
Step 1: main() starts
Stack: Program binary:
┌──────────────────────────────┐ ┌─────┬─────┬─────┬─────┬─────┐
│ main() │ │ 'A' │ 'l' │ 'i' │ 'c' │ 'e' │
│ ├ x: i32 = 42 │ └─────┴─────┴─────┴─────┴─────┘
│ ├ name: &str │ ▲
│ │ ptr ─────────────────────┼─────────┘
│ │ len: 5 │
│ └ result: String = ??? │ Heap: (nothing yet)
└──────────────────────────────┘
fn main() { let x = 42; // Stack variable let name = "Alice"; // Points into the program let result = process_data(x, name); println!("{}", result); } fn process_data(num: i32, text: &str) -> String { let mut doubled = num * 2; // Stack variable // A bracketed scope creates its own mini-stack frame! { let temp_multiplier = 10; // New scope variable let temp_result = doubled * temp_multiplier; // Another scope variable println!("Temp calculation: {}", temp_result); doubled = doubled + 1; // Modify outer variable } // temp_multiplier and temp_result are destroyed here! let greeting = format!("Hello {}, your number is {}", text, doubled); greeting // Return String (heap data) }
Step 2: Call process_data(x, name)
Function arguments and local variable doubled are added to the stack:
Stack: Program binary:
┌──────────────────────────────┐ ┌─────┬─────┬─────┬─────┬─────┐
│ process_data() │ │ 'A' │ 'l' │ 'i' │ 'c' │ 'e' │
│ ├ num: i32 = 42 │ └─────┴─────┴─────┴─────┴─────┘
│ ├ text: &str │ ▲ ▲
│ │ ptr ─────────────────────┼─────────┘ │
│ │ len: 5 │ │
│ ├ doubled: i32 = 84 │ │
│ └ greeting: String = ??? │ │
├──────────────────────────────┤ │ Heap: (nothing yet)
│ main() │ │
│ ├ x: i32 = 42 │ │
│ ├ name: &str │ │
│ │ ptr ─────────────────────┼───────────────┘
│ │ len: 5 │
│ └ result: String = ??? │
└──────────────────────────────┘
fn main() { let x = 42; // Stack variable let name = "Alice"; // Points into the program let result = process_data(x, name); println!("{}", result); } fn process_data(num: i32, text: &str) -> String { let mut doubled = num * 2; // Stack variable // A bracketed scope creates its own mini-stack frame! { let temp_multiplier = 10; // New scope variable let temp_result = doubled * temp_multiplier; // Another scope variable println!("Temp calculation: {}", temp_result); doubled = doubled + 1; // Modify outer variable } // temp_multiplier and temp_result are destroyed here! let greeting = format!("Hello {}, your number is {}", text, doubled); greeting // Return String (heap data) }
Step 3: Enter the bracketed scope {}
The scope creates its own mini-stack frame with temporary variables:
Stack:
┌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┐
╎ { scope } ╎
╎ ├ temp_multiplier: i32 = 10 ╎
╎ └ temp_result: i32 = 840 ╎
└╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┘ Program binary:
┌──────────────────────────────┐ ┌─────┬─────┬─────┬─────┬─────┐
│ process_data() │ │ 'A' │ 'l' │ 'i' │ 'c' │ 'e' │
│ ├ num: i32 = 42 │ └─────┴─────┴─────┴─────┴─────┘
│ ├ text: &str │ ▲ ▲
│ │ ptr ─────────────────────┼─────────┘ │
│ │ len: 5 │ │
│ ├ doubled: i32 = 85 │ <- was 84 │
│ └ greeting: String = ??? │ │
├──────────────────────────────┤ │ Heap: (nothing yet)
│ main() │ │
│ ├ x: i32 = 42 │ │
│ ├ name: &str │ │
│ │ ptr ─────────────────────┼───────────────┘
│ │ len: 5 │
│ └ result: String = ??? │
└──────────────────────────────┘
fn main() { let x = 42; // Stack variable let name = "Alice"; // Points into the program let result = process_data(x, name); println!("{}", result); } fn process_data(num: i32, text: &str) -> String { let mut doubled = num * 2; // Stack variable // A bracketed scope creates its own mini-stack frame! { let temp_multiplier = 10; // New scope variable let temp_result = doubled * temp_multiplier; // Another scope variable println!("Temp calculation: {}", temp_result); doubled = doubled + 1; // Modify outer variable } // temp_multiplier and temp_result are destroyed here! let greeting = format!("Hello {}, your number is {}", text, doubled); greeting // Return String (heap data) }
Step 4: Exit the bracketed scope
The mini-frame is gone, and temp_multiplier and temp_result with it. doubled keeps its new value:
Stack: Program binary:
┌──────────────────────────────┐ ┌─────┬─────┬─────┬─────┬─────┐
│ process_data() │ │ 'A' │ 'l' │ 'i' │ 'c' │ 'e' │
│ ├ num: i32 = 42 │ └─────┴─────┴─────┴─────┴─────┘
│ ├ text: &str │ ▲ ▲
│ │ ptr ─────────────────────┼─────────┘ │
│ │ len: 5 │ │
│ ├ doubled: i32 = 85 │ │
│ └ greeting: String = ??? │ │
├──────────────────────────────┤ │ Heap: (nothing yet)
│ main() │ │
│ ├ x: i32 = 42 │ │
│ ├ name: &str │ │
│ │ ptr ─────────────────────┼───────────────┘
│ │ len: 5 │
│ └ result: String = ??? │
└──────────────────────────────┘
fn main() { let x = 42; // Stack variable let name = "Alice"; // Points into the program let result = process_data(x, name); println!("{}", result); } fn process_data(num: i32, text: &str) -> String { let mut doubled = num * 2; // Stack variable // A bracketed scope creates its own mini-stack frame! { let temp_multiplier = 10; // New scope variable let temp_result = doubled * temp_multiplier; // Another scope variable println!("Temp calculation: {}", temp_result); doubled = doubled + 1; // Modify outer variable } // temp_multiplier and temp_result are destroyed here! let greeting = format!("Hello {}, your number is {}", text, doubled); greeting // Return String (heap data) }
Step 5: greeting is built
format! makes a new String, with its text on the heap. The first heap allocation in this whole program.
Stack: Program binary:
┌──────────────────────────────┐ ┌─────┬─────┬─────┬─────┬─────┐
│ process_data() │ │ 'A' │ 'l' │ 'i' │ 'c' │ 'e' │
│ ├ num: i32 = 42 │ └─────┴─────┴─────┴─────┴─────┘
│ ├ text: &str │ ▲ ▲
│ │ ptr ─────────────────────┼─────────┘ │
│ │ len: 5 │ │
│ ├ doubled: i32 = 85 │ Heap: │
│ └ greeting: String │ ┌────────────────────┐ │
│ ptr ─────────────────────┼──────────▶│ "Hello Alice, your │ │
│ len: 30 │ │ number is 85" │ │
│ cap: 46 │ └────────────────────┘ │
├──────────────────────────────┤ │
│ main() │ │
│ ├ x: i32 = 42 │ │
│ ├ name: &str │ │
│ │ ptr ─────────────────────┼───────────────────────────────────┘
│ │ len: 5 │
│ └ result: String = ??? │
└──────────────────────────────┘
fn main() { let x = 42; // Stack variable let name = "Alice"; // Points into the program let result = process_data(x, name); println!("{}", result); } fn process_data(num: i32, text: &str) -> String { let mut doubled = num * 2; // Stack variable // A bracketed scope creates its own mini-stack frame! { let temp_multiplier = 10; // New scope variable let temp_result = doubled * temp_multiplier; // Another scope variable println!("Temp calculation: {}", temp_result); doubled = doubled + 1; // Modify outer variable } // temp_multiplier and temp_result are destroyed here! let greeting = format!("Hello {}, your number is {}", text, doubled); greeting // Return String (heap data) }
Steps 5 to 7. Start a fresh drawing here, from the moment greeting is built. Same rule: update it, do not redraw it.
Step 6: process_data() returns
process_data's frame is gone, greeting with it. The text it pointed at is still on the heap, and now result points at it:
Stack: Program binary:
┌──────────────────────────────┐ ┌─────┬─────┬─────┬─────┬─────┐
│ main() │ │ 'A' │ 'l' │ 'i' │ 'c' │ 'e' │
│ ├ x: i32 = 42 │ └─────┴─────┴─────┴─────┴─────┘
│ ├ name: &str │ ▲
│ │ ptr ─────────────────────┼─────────┘
│ │ len: 5 │ Heap:
│ └ result: String │ ┌────────────────────┐
│ ptr ─────────────────────┼──────────▶│ "Hello Alice, your │
│ len: 30 │ │ number is 85" │
│ cap: 46 │ └────────────────────┘
└──────────────────────────────┘
fn main() { let x = 42; // Stack variable let name = "Alice"; // Points into the program let result = process_data(x, name); println!("{}", result); } fn process_data(num: i32, text: &str) -> String { let mut doubled = num * 2; // Stack variable // A bracketed scope creates its own mini-stack frame! { let temp_multiplier = 10; // New scope variable let temp_result = doubled * temp_multiplier; // Another scope variable println!("Temp calculation: {}", temp_result); doubled = doubled + 1; // Modify outer variable } // temp_multiplier and temp_result are destroyed here! let greeting = format!("Hello {}, your number is {}", text, doubled); greeting // Return String (heap data) }
Step 7: main() ends
All stack data is cleaned up, and Rust automatically frees the heap data:
Stack: Heap:
┌─────────┐ ┌─────────────┐
│ (empty) │ │ (cleaned up │
└─────────┘ │ by Rust!) │
└─────────────┘
fn main() { let x = 42; // Stack variable let name = "Alice"; // Points into the program let result = process_data(x, name); println!("{}", result); } fn process_data(num: i32, text: &str) -> String { let mut doubled = num * 2; // Stack variable // A bracketed scope creates its own mini-stack frame! { let temp_multiplier = 10; // New scope variable let temp_result = doubled * temp_multiplier; // Another scope variable println!("Temp calculation: {}", temp_result); doubled = doubled + 1; // Modify outer variable } // temp_multiplier and temp_result are destroyed here! let greeting = format!("Hello {}, your number is {}", text, doubled); greeting // Return String (heap data) }
Take-aways from this example
- Stack builds up as functions are called, shrinks as they return
- Bracketed scopes
{}create mini-stack frames within functions - Variables in scopes are destroyed when the scope ends, changes to outer variables persist
- Heap data can outlive the function that created it, when the function returns it
- Rust automatically cleans up heap data when no one owns it anymore
Activity 18, Problem 3
Finish Problem 3 on your sheet, and Problem 4 if you have time. Hand it in on your way out.
See activities/activity_18.md.