Sub topic 6
Catching out-of-bounds access and use-after-free
This chapter assumes you can write basic unsafe Rust with raw pointers, you know how Vec and Box own heap memory, and you can run cargo +nightly miri run as shown in the previous chapters. Here you will see how Miri catches the two most common memory errors, and how to read and fix each report.
Why these two errors matter
Both errors break the same rule. A pointer may only be used to access memory that is still allocated, and only inside the bounds of the allocation it came from.
- An out-of-bounds access reads or writes past the end (or before the start) of an allocation.
- A use-after-free accesses an allocation that has already been deallocated.
Natively, both often seem to work. The bytes next to a Vec buffer usually hold something readable, and freed memory usually still contains the old value until the allocator reuses it. A test can pass for months and then fail after an unrelated change moves things around. Miri does not depend on what happens to be in memory, because it tracks every allocation and every pointer.
How Miri tracks allocations
Miri gives each allocation an identity and a size. Every pointer carries a tag that says which allocation it may access. When your program dereferences a pointer, Miri checks three things:
- The allocation the pointer refers to is still live.
- The whole accessed range fits inside that allocation.
- The pointer is allowed to access it (this is where the aliasing models from a later chapter apply).
A failure of any check stops the program with an error. Miri does not guess and continue. This is why a Miri error is reliable evidence of a bug, and why it points at the first bad access rather than at a later crash.
Out-of-bounds access
Start with a program that reads one element past the end of a three-element Vec.
fn main() {
let v = vec![1, 2, 3];
let p = v.as_ptr();
let x = unsafe { *p.add(3) };
println!("{x}");
}Run natively, this usually prints some number without complaint. Run it under Miri:
cargo +nightly miri runMiri stops with an error similar to this (exact wording and addresses vary between versions):
error: Undefined Behavior: memory access failed: attempting to access 4 bytes, but got alloc1234+0xc which is at or beyond the end of the allocation of size 12 bytes
--> src/main.rs:4:22
|
4 | let x = unsafe { *p.add(3) };
| ^^^^^^^^^ memory access failed ...Read it in pieces:
- The headline names the rule that was broken: the access of 4 bytes starts at offset
0xc(12), and the allocation is exactly 12 bytes long (threei32values). - The arrow gives the source line of the bad access, here the dereference on line 4.
- Later notes show where the allocation was created, which for a
Vecpoints into the allocator call insidevec!.
Computing the pointer is not the error
The call p.add(3) computes a pointer one element past the end. That is allowed, because Rust permits a pointer one-past-the-end of an allocation. The error occurs at the dereference, *. Computing a pointer farther than one past the end is a separate problem: add requires the result to stay within the allocation (or one past its end), so p.add(4) is undefined behavior even without a dereference. Miri reports that case at the add call.
Partial overlaps are caught too
Miri checks the whole range. Reading a u32 that starts two bytes before the end of an allocation fails even though the first two bytes are valid. Miri does not need the access to start outside the allocation.
Fixing it
Use safe indexing, or check the length before the unsafe access.
fn main() {
let v = vec![1, 2, 3];
let p = v.as_ptr();
let i = 2;
assert!(i < v.len());
let x = unsafe { *p.add(i) };
println!("{x}");
}When you can, prefer v.get(i) or v[i]. A bounds check costs very little, and it removes the whole class of error.
Use-after-free
Now the second error. This program frees a Box and then reads through a raw pointer that still points to it.
fn main() {
let p = Box::into_raw(Box::new(5));
unsafe {
drop(Box::from_raw(p));
println!("{}", *p);
}
}Box::into_raw gives up ownership and returns a raw pointer. Box::from_raw rebuilds a Box from it, and drop frees the allocation. The final *p reads memory that no longer belongs to the program. Natively this often prints 5, since the allocator has not reused the memory yet.
Miri reports something like:
error: Undefined Behavior: memory access failed: alloc1234 has been freed, so this pointer is dangling
--> src/main.rs:5:24
|
5 | println!("{}", *p);
| ^^ memory access failed ...
|
help: alloc1234 was allocated here:
--> src/main.rs:2:30
help: alloc1234 was deallocated here:
--> src/main.rs:4:9Use-after-free reports are among the most useful Miri output, because they give three locations:
| Location | What it tells you |
|---|---|
| The access | The line that used the dangling pointer. |
| The allocation | Where the memory was created. |
| The deallocation | Where the memory was freed, usually the real cause. |
Start with the deallocation. The bug is usually that something freed the memory too early, or that a pointer outlived its owner, and the access line only shows where the problem became visible.
Fixing it
The pointer must not be used after the free. Either finish using the value first, or keep ownership.
fn main() {
let p = Box::into_raw(Box::new(5));
unsafe {
println!("{}", *p);
drop(Box::from_raw(p));
}
}Better still, avoid the raw pointer. A plain Box or reference makes the borrow checker reject the use after drop at compile time.
Related errors Miri reports in the same family
The same machinery catches several neighboring bugs. They produce similar reports:
- Double free. Calling
Box::from_rawtwice on the same pointer deallocates twice. Miri reports the second deallocation, because the allocation is already freed. - Wrong layout on deallocation. Freeing memory with a different size or alignment than it was allocated with is undefined behavior, and Miri reports the mismatch.
- Memory leaks. Miri reports memory that is still allocated when the program exits. A leak is not undefined behavior, but it often signals a missing
drop. You can disable the check with-Zmiri-ignore-leaksthroughMIRIFLAGSwhen a leak is intended. - Misaligned access. Reading a
u32through a pointer that is not 4-byte aligned is undefined behavior, even on hardware that tolerates it.
A working routine for these reports
- Read the headline to learn which rule was broken: bounds, freed, or something else.
- Go to the arrow location, the access that failed.
- For a freed allocation, read the "allocated here" and "deallocated here" notes. For an out-of-bounds access, compare the offset with the size in the message.
- Decide whether the access is wrong or the lifetime or length bookkeeping is wrong. Fix the cause, not the symptom.
- Re-run until Miri passes, then keep the program as a regression test.
Limits of what you have seen
Miri only checks accesses that actually execute. If the out-of-bounds read sits in a branch that your test never takes, Miri will not report it. Miri also treats each run as one concrete execution, so a bug that depends on particular input needs a test that supplies that input. A later chapter covers these limits in full.
Exercise
The program below runs natively without visible problems. Does Miri report an error, and if so, on which line and why? How would you fix it? fn main() { let mut v = vec![10u8, 20, 30]; let p = v.asmutptr(); v.push(40); unsafe { *p = 99; } println!("{:?}", v); }
Show answer
Miri reports a use-after-free at *p = 99. Pushing to a Vec with capacity 3 forces it to reallocate. The old buffer is freed and the contents move to a new one, so p now dangles. The "deallocated here" note points into the push call. To fix it, get the pointer after the push (move as_mut_ptr() below v.push(40)), or write through safe indexing with v[0] = 99.