Lecture 17 - The stack: frames and why it's fast
Announcements
Where does "undo" live?
How does your computer know what to undo? And why, if you keep hitting it, does it eventually stop?
Answer.
Every edit gets pushed onto a pile. Undo takes the top one off.
The most recent thing you did is the first thing to come back.
The pile has a fixed size, so old edits fall off the bottom.
That pile is called a stack, and today we'll see your program has one too.
Why we are about to spend three weeks on memory
Let me tell you some stories.
Heartbleed, 2014. A read past the end of a buffer, in security software. Leaked passwords, private keys, and personal data from roughly 17% of the world's secure web servers.
WannaCry, 2017
A buffer overflow in a Windows networking protocol. 200,000+ computers in 150 countries, including hospitals in the UK, about $4 billion in damages.
Still happening
Zoom, 2026. A use-after-free in the annotation tool let one meeting participant run code on another's computer. Patched this year.
In C and C++, roughly 70% of security vulnerabilities are memory safety bugs, according to both Microsoft and Google.
In safe Rust, none of these can happen. The use-after-free is a compiler error. The out-of-bounds reads stop the program on the spot, before anything leaks. A crash is a brief annoyance rather than a disaster.
Not every rewrite is about security
Dropbox, 2020. Their file-sync engine was written in Python. After years of bugs that were "extremely unlikely" but kept showing up anyway, they rewrote the whole engine in Rust, and the compiler now rules out whole classes of those bugs.
The rules that stop the security bug also stop the ordinary ones.
So here is the deal
For the next three weeks, Rust is going to tell you "no" a lot.
Every one of those refusals is one of these bugs, turned into a compiler error. You are going to learn the rules, and you are going to learn what each rule is for.
We start today with where your data actually is.
Learning Objectives
By the end of today, you should be able to:
- Explain the difference between RAM and storage, and say which one "memory" means
- Explain what a memory address is
- Name three approaches to memory management and one language that uses each
- Describe what a stack frame holds and when it appears and disappears
- Explain what a stack overflow is and what causes one
What is computer memory?
Think of your computer's memory like a giant filing cabinet.
- Each drawer holds one piece of information
- Each drawer has a unique number (an address)
- Your program can put things in drawers and take things out
What's the difference between RAM and storage (hard drive)?
RAM (Random Access Memory)
- Where your program's data lives while it is running
- Fast
- Temporary: gone when you close the program or power off
- This is why restarting your machine solves 50% of problems!
- Usually a few to a few dozen gigabytes
Storage (SSD or hard drive)
- Where your files live
- Much slower to read, several orders of magnitude
- Permanent: survives a reboot
- Usually hundreds of gigabytes or terabytes
When we say "memory" in this course, we mean RAM.
Which of these is RAM?
A helpful metaphor for RAM
Picture a very long street with billions of houses on it, numbered from 0.
- Every house is exactly the same size: one byte, which is 8 bits
- Every house has exactly one number and it's unique to that house
- To read or write anything, you need the number
That number is an address.
How big is a byte? Big enough for one u8 (0 to 255), or one i8 (-128 to 127), or one bool (which only needs one bit but gets a whole byte anyway, because a byte is the smallest thing the machine can address).
An i32 needs 4 bytes, so it fills four houses in a row.
Memory Addresses - Like Street Addresses
Let's look at some real ones.
fn main() { let x1: u8 = 10; let x2: u32 = 20; let x3: u32 = 30; // {:p} prints in address form. The p is for "pointer". // &x asks Rust for the address of x. println!("address of x1 {:p}", &x1); println!("address of x2 {:p}", &x2); println!("address of x3 {:p}", &x3); }
Rust prints addresses in hexadecimal, because they get very large.
Three things to notice. Look at the output, not at the slide.
- The addresses are in order: x1, then x2, then x3
- x2 is one byte past x1, because x1 is a
u8, which is one byte - x3 is four bytes past x2, because x2 is a
u32, which is four bytes
The variables were laid down one after another, each taking exactly as much room as its type needs.
How Memory is Organized - The Big Picture
Your program does not get the whole street. It gets a few neighborhoods, and they are used for different things.
Today: the stack. Wednesday: the heap.
The Stack: Like a literal stack of plates
The idea: Last thing you put on, first thing you take off
fn main() { // Stack: [ ] let x = 42; // Stack: [x=42 ] let y = true; // Stack: [x=42, y=true] println!("{}", x); } // Stack: [ ] ← Everything cleaned up automatically!
Stack characteristics:
- Super fast - just "put on top" or "take off top"
- Limited size - like a small tower of plates
- Automatic cleanup - when a function ends, its "plates" are removed
- Size must be known - each "plate" is a fixed size
Most Rust data you've seen lives on the stack: i32, bool, char, arrays, tuples
This one's worth saying again...
Size must be known, at compile time.
The stack works because everything is laid down in order with no gaps. To put x2 right after x1, the compiler has to know how big x1 is before the program runs.
So what cannot go on the stack? Anything that can grow.
- A
Stringyou push characters onto. - A
Vecyou push elements onto. - A file you read in, whose length you do not know until you read it
Those belong in tomorrow's lecture.
Stack Frames: Organized Sections
Each function call gets its own organized section called a stack frame
Stack frame holds all the data for one function call:
- Function parameters
- Local variables
- Return address (where to go back when function ends)
- Other bookkeeping info
Stack Memory:
┌─────────────────┐ ← Top of stack
│ Function B │ ← Stack frame for Function B (called by A)
│ parameters │
│ local vars │
├─────────────────┤
│ Function A │ ← Stack frame for Function A (main)
│ parameters │
│ local vars │
│ return info │
└─────────────────┘ ← Bottom of stack
When a function returns, its whole frame is thrown away at once. Nobody has to walk through it and clean up. The top of the stack just moves back down.
That is why the stack is fast.
Activity 17, Problem 1: your first stack
See Problem 1 on Activity 17.
┌──────────────────────────┐
│ add_one │
│ n: i32 = 1 │
│ result: i32 = 2 │
└──────────────────────────┘
┌──────────────────────────┐
│ main │
│ a: i32 = 1 │
│ b: i32 = ??? │
└──────────────────────────┘
Two frames. b is ??? because add_one has not returned yet. When it does, its frame disappears and 2 is copied into b.
Draw this out! You will be asked to draw one on the next midterm, and the more you practice as we go the more comfortable you'll be then.
A scope inside a function: shadowing
A { } block gets a mini-frame: a dashed box stacked on top of its function's frame. It pops off at the closing brace, taking its variables with it.
To find a variable, read from the top down, and stop at a solid line.
fn main() { let x = 5; println!("before: {}", x); { let x = 7; // DRAW HERE println!("inside: {}", x); } println!("after: {}", x); }
┌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┐
╎ { scope } ╎
╎ x: i32 = 7 ╎
└╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┘
┌──────────────────────────┐
│ main │
│ x: i32 = 5 │
└──────────────────────────┘
let makes a second x in the mini-frame. Reading from the top, println! finds that one first. At the brace the mini-frame pops off, and the x on top is main's 5 again.
A scope inside a function: mut
Same program, but mut on the outside and no let on the inside.
fn main() { let mut x = 5; println!("before: {}", x); { x = 7; // DRAW HERE println!("inside: {}", x); } println!("after: {}", x); }
┌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┐
╎ { scope } ╎
╎ (nothing new) ╎
└╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┘
┌──────────────────────────┐
│ main │
│ x: i32 = 7 (was 5) │
└──────────────────────────┘
No let, so the mini-frame has no x. Reading down, x = 7 falls through the dashed line and writes into main's x, which is still there after the brace.
Activity 17, Problem 2: a scope inside a function
See Problem 2 on Activity 17.
┌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┐
╎ { scope } ╎
╎ bonus: i32 = 5 ╎
╎ doubled: i32 = 20 ╎
└╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┘
┌──────────────────────────┐
│ main │
│ total: i32 = 20 │
│ (was 10) │
└──────────────────────────┘
There is no let on the total line, so the mini-frame gets no total of its own. After the brace, only total is left, and it is still 20.
Stack Overflow - A Real Problem!
The stack has a fixed size, usually a few megabytes. Two ways to run out of space.
Way 1: too many frames.
fn count_forever(n: u64) -> u64 { count_forever(n + 1) // never returns, so the frame never goes away } fn main() { println!("{}", count_forever(0)); }
Every call adds a frame. Nothing ever returns. The stack grows until it hits its limit and the program dies.
Yes, the website is named after this! It is a very common way programs dies in languages that let you recurse.
Way 2: one frame that is too big.
fn main() { let small = [0u8; 1000]; // fine // let huge = [0u8; 10_000_000]; // 10 MB in one frame: crash }
Tomorrow you will learn the fix for way 2, which is to put the big thing somewhere else.
Three Approaches to Memory Management
Different programming languages handle memory differently:
-
Manual (C/C++): "You figure it out!"
- Programmer manually asks for memory and gives it back (C:
malloc/free) - Super fast, but easy to make dangerous mistakes
- Programmer manually asks for memory and gives it back (C:
-
Garbage Collection (Python/Java): "I'll handle it automatically!"
- Language automatically cleans up unused memory
- Safe but can cause random slowdowns
-
Ownership (Rust): "I'll help you get it right!"
- Compiler enforces rules to prevent mistakes
- Fast AND safe
This is why Rust can seem picky sometimes - it's preventing memory bugs!
The same three, as a spectrum
Control/Performance <----------------------------> Safety/Ease
C/C++ Rust Java/Go Python
│ │ │ │
Manual Ownership Garbage Garbage
Memory System Collection Collection
(pauses at (mostly frees
unpredictable things the moment
times) they are unused)
│ │ │ │
Fast, Unsafe Fast, Safe Slower, Safe Slowest, Safe
Rust's claim is that it broke the trade-off - this part of the course looks at Rust's "ownership system" to see how the magic happens.
Take-aways
- Memory is a numbered strip of one-byte cells, and an address is a cell number
- Your program's data lives in a few regions; today's is the stack
- Each function call gets a stack frame, thrown away whole when the function returns
- The stack is fast because it is ordered and automatic
- It is ordered and automatic because every size is known ahead of time
Tomorrow: what happens when the size is not known ahead of time.
Activity 17, Problems 3 and 4
Finish the last two problems on your sheet, and hand it in on your way out.
See activities/activity_17.md.