Lecture 20 - Pointer danger: seven ways C loses your memory
Announcements
Where we left off
Friday: a pointer (and &) holds an address, and dereferencing (*) follows it.
To * a raw pointer we needed an unsafe block, which means we are taking responsibility.
Today: responsibility for what, exactly?
Learning objectives
By the end of today, you should be able to:
- Read a short program, in
unsafeRust or in C, that allocates and frees memory by hand, and say what each line does - Name seven ways a pointer can be wrong
- Explain what Rust does to avoid these issues
You will write some unsafe Rust in Project 2. On exams, you may need to read it, but hand-coding is safe Rust only.
Doing the heap by hand
A line we have written a few times:
let s = "hello".to_string();
Here is what it does under the hood:
fn main() { unsafe { // 1. ask the heap for five bytes let ptr: *mut u8 = libc::malloc(5) as *mut u8; // 2. put the letters in them std::ptr::write(ptr as *mut [u8; 5], *b"hello"); println!("letters at {:p}", ptr); } }
malloc(5) means "give me five bytes". It hands back a pointer to them.
This is core to checkpoint 2. libc::malloc is your project's MALLOC.malloc, same shape. Put size_of::<T>() * n where the 5 is and you have the line your push writes when it runs out of room.
That is the whole heap side of it.
What to_string does after step 2 is remember three numbers on the stack:
- where the letters are (
ptr) - how many there are (
len) - how much room there is (
cap)
Notice malloc does not know or care that you wanted letters when it decided what memory to take!
Allocated is not initialized
Between step 1 and step 2, what is in those five bytes?
Whatever was there before. malloc reserves space; it does not clear it.
You often get zeros, because allocators frequently hand out zeroed pages. You cannot rely on that, so if you try to read it, bad things can happen.
Writing before reading
So you have to write the value in before you read anything out. This time, a whole String handle on the heap, not just its letters:
fn main() { unsafe { let my_ptr: *mut String = libc::malloc(size_of::<String>()) as *mut String; std::ptr::write(my_ptr, String::from("hello!")); println!("{}", *my_ptr); } }
Three steps where you used to write one line: ask for bytes, put a value in them, then use it.
And you have to give it back
The stack cleans up after itself. The heap does not.
fn main() { unsafe { let my_ptr: *mut String = libc::malloc(size_of::<String>()) as *mut String; std::ptr::write(my_ptr, String::from("hello!")); println!("{}", *my_ptr); std::ptr::read(my_ptr); // frees the letters libc::free(my_ptr as *mut libc::c_void); // frees the handle } }
Why two lines to clean up one thing?
Two blocks, two frees
Stack: Heap:
┌───────────┐ the handle: 24 bytes, from your malloc
│ my_ptr ───┼──────▶┌──────────────┐
└───────────┘ │ ptr ─────────┼───▶ the letters: from String::from
│ len: 6 │ ┌───┬───┬───┬───┬───┬───┐
│ cap: 6 │ │ h │ e │ l │ l │ o │ ! │
└──────────────┘ └───┴───┴───┴───┴───┴───┘
Usually a String's handle sits on the stack. Here we put it on the heap ourselves, so there are two blocks, and each needs its own free.
libc::freefrees the handle, the block we asked forstd::ptr::readleads to the letters being freed
read is a misleading name. Reading a book doesn't destroy it, but ptr::read does: think of it as "read and destroy", so it frees the letters.
Without read the letters would stay on the heap forever. This is a leak inside a cleanup, the cause of many real-world bugs.
Why this matters
Three numbers from teams that maintain some of the biggest C and C++ codebases in the world:
- Microsoft, 2019: about 70% of the security bugs they fix each year are memory-safety bugs
- Chrome, 2020: about 70% of serious security bugs are memory-safety bugs. Half of those are use-after-free, bug 2 coming up
- Android, 2024: new code has been written in memory-safe languages, Rust among them, since 2019. Memory-safety bugs fell from 76% of Android's vulnerabilities to 24%
These are some of the best-funded engineering teams on earth, and they still make these mistakes in C and C++.
Enough C to read the bugs
Everything coming up is C. You need four things.
| C | What it is | Rust equivalent |
|---|---|---|
int* ptr | a pointer to an int | *mut i32 |
malloc(100) | ask for 100 bytes | libc::malloc(100) |
free(data) | give them back | libc::free(data) |
NULL | a pointer to nothing, address 0 | none in safe Rust |
The * in a type means "pointer to".
The * in an expression means "follow it".
Same two meanings as Rust.
Let's look at some bugs.
Bug 1: Memory leaks
What happens: never free it
// C code - compiles, runs, and quietly grows
void greet() {
char* name = malloc(100);
strcpy(name, "hello");
printf("%s", name);
} // No free(name): 100 bytes gone, every call
During greet(): After greet() returns:
┌──────────────┐ ░░░░░░░░░░░░░░░░
│ greet() │ ┌───────┐ ░ greet() gone ░ ┌───────┐
│ └ name ──────┼───▶│ hello │ ░░░░░░░░░░░░░░░░ │ hello │
└──────────────┘ └───────┘ └───────┘
Stack Heap ▲
no arrow left
When greet returns, name goes with its frame. The 100 bytes stay, and with no arrow left, nothing can ever free them.
Why it's dangerous:
- Nothing crashes. The program just keeps growing
- A server that runs for weeks eventually runs out of memory
- The bug is a line that isn't there
Rust: frees a value when its owner goes out of scope (more Wednesday). But this doesn't stop all leaks... (There was drama. People called it the "leakpocalypse". But you'll probably never run into it.)
Project 2: your FastVec lives in unsafe, where nothing frees for you. Checkpoint 3's Drop has you writing that free.
Bug 2: Use-after-free
What happens: free it, then use it anyway
// C code - compiles but UNSAFE!
char* data = malloc(100);
strcpy(data, "hello");
free(data); // Memory handed back to the allocator
// Later...
printf("%s", data); // Reading freed memory!
// Might work, might crash, might read garbage
Why it's dangerous:
- The memory may already belong to something else
- Can expose passwords, card numbers
- Works in testing, crashes in production
Rust: won't compile a use of a value after it is freed.
Bug 3: Double-free
What happens: free the same memory twice
// C code - compiles but CRASHES!
char* ptr1 = malloc(100);
char* ptr2 = ptr1; // Two pointers to same memory
free(ptr1); // Free once
free(ptr2); // Free again! CRASH or worse
Stack: Heap:
┌──────────────────┐
│ main() │
│ ├ ptr1 ──────────┼──┐ ┌───────────┐
│ └ ptr2 ──────────┼──┴───▶│ 100 bytes │
└──────────────────┘ └───────────┘
Two arrows, one block. After free(ptr1), ptr2 still holds the same address, so free(ptr2) hands back a block that is no longer yours.
Why it's dangerous:
- Corrupts the allocator's bookkeeping
- A known route to security exploits
Rust: one owner, so one free.
We can write this one in Rust too.
fn main() { unsafe { let ptr0: *mut i32 = libc::malloc(size_of::<i32>() * 2) as *mut i32; libc::free(ptr0 as *mut libc::c_void); libc::free(ptr0 as *mut libc::c_void); } }
Bug 4: Dangling pointers
What happens: a pointer outlives what it points to
// C code - compiles but UNSAFE!
int* get_number() {
int x = 42;
return &x; // Returning pointer to local variable!
} // x's frame is thrown away here
int main() {
int* ptr = get_number();
printf("%d", *ptr); // Reading a dead frame!
}
Draw the stack. What happens to get_number's frame at the closing brace?
Stack:
░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░ get_number() (gone) ░
░ └ x: int = 42 ░◀─┐
░░░░░░░░░░░░░░░░░░░░░░░░░░░░ │
┌──────────────────────────┐ │
│ main() │ │
│ └ ptr: int* ─────────────┼──┘
└──────────────────────────┘
It is thrown away. The address still looks fine, but it points into a frame that no longer exists, and the next function call writes over it.
Rust: a reference can't outlive its data. Friday's last slide.
Bug 5: Buffer overflow
What happens: writing past the end of an array
// C code - compiles but CRASHES!
int arr[5];
for (int i = 0; i <= 5; i++) { // Off by one!
arr[i] = i; // i = 5 writes past the end
}
[0] [1] [2] [3] [4] [5]
┌─────┬─────┬─────┬─────┬─────┐ ┌╌╌╌╌╌┐
│ 0 │ 1 │ 2 │ 3 │ 4 │ ╎ 5 ╎
└─────┴─────┴─────┴─────┴─────┘ └╌╌╌╌╌┘
└─────── arr, 5 ints ───────┘ someone else's
arr[5] lands in memory that belongs to something else, and C does not check.
Why it's dangerous:
- Overwrites whatever comes next, other variables included
- Can overwrite where the function returns to: a classic exploit
- Heartbleed (2014): the same bug while reading. Leaked servers' passwords and keys
Rust: checks every index, and panics instead.
Bug 6: Null pointers
What happens: following a pointer to nothing
// C code - compiles but CRASHES!
char* find_name(int id) {
if (id == 1) {
return "Alice";
}
return NULL; // "No name" is spelled NULL
}
int main() {
char* name = find_name(2);
printf("%c", name[0]); // Follows NULL. Crash
}
Stack:
┌──────────────────────────┐
│ main() │
│ └ name: char* = NULL ────┼──▶ address 0: nothing here
└──────────────────────────┘
NULL is address 0, and address 0 is never yours. Following it crashes the program.
Why it's dangerous:
- Any pointer might be
NULL mallocreturnsNULLwhen it fails. Easy to forget to check- Its inventor, Tony Hoare (1965), called it his "billion-dollar mistake"
Rust: a reference is never null! "Maybe nothing" is Option, and you must handle None. We've done this a lot now!
Bug 7: Data races
What happens: two threads, same memory, at least one writing
// C code with threads - compiles but RACE CONDITION!
int counter = 0;
void* increment(void* arg) {
for (int i = 0; i < 1000000; i++) {
counter++; // Not thread-safe!
}
}
// Run two threads...
// Expected: counter = 2,000,000
// Actual: counter = ??? (unpredictable!)
Why it's dangerous:
- A different answer every run
- Nearly impossible to reproduce
Rust: refuses to compile it. We'll fix it by the end of the term.
Memory safety: summary
| Bug Type | What It Is | How Rust Prevents |
|---|---|---|
| Leak | Never freeing | Ownership, mostly |
| Use-after-free | Using freed memory | Borrow checker |
| Double-free | Freeing twice | Ownership |
| Dangling pointer | Pointer outlives data | Lifetimes |
| Buffer overflow | Array out of bounds | Bounds checking |
| Null pointer | Following an address to nothing | Option |
| Data race | Concurrent unsynchronized access | (We'll see!) |
All of them caught at compile time, except bounds, which panics safely at run time, and leaks, which Rust only mostly prevents.
Look at the middle column - they're generally all mistakes about who is allowed to access what and when.
What Rust's protection costs:
- a bit of time (checking bounds)
- annoyance from a picky compiler
But it's worth it!
What we signed for when we use unsafe
Inside unsafe, all these bugs become possible again:
- Forget to
free: leak. (Project 2 checkpoint 3!) - Read through a pointer after
free: use-after-free freethe same pointer twice: double-free- Write past the end of what you asked
mallocfor: buffer overflow - Follow a null pointer: crash
You'll run into many of these in Project 2!
Write down why each unsafe block is OK. Rust programmers put a // SAFETY: comment above every one, like // SAFETY: p came from malloc, and i < len, to help keep track of what's happening and catch bugs!
Preview of ownership - Bugs happen when no one is responsible
In every memory bug there are several pointers to one piece of data, and no answer to a simple question:
a variable ───────────┐
▼
┌──────────┐
a list entry ───▶│ the data │◀─── another function
└──────────┘
Whose is it?
C has no answer.
Rust answers at compile time, by insisting there is exactly one owner and tracking who it is.
That answer is called ownership, and we start on it next time!
Activity 20
Let's talk glitches!
- I'll play a video from YouTube - you make note of what kinds of bugs you see
- You'll answer two questions on Gradescope about the video
- If we have time we'll watch a second one