Sub topic 6
Catching out-of-bounds access and use-after-free
This chapter assumes you know Rust ownership, raw pointers and basic unsafe. It also assumes you can run cargo +nightly miri run, which an earlier chapter covered. Here you will see how Miri reports the two most common memory errors and how to read the reports.
Why these errors hide
Raw pointers skip the bounds and lifetime checks that references get. A read past the end of a buffer, or through a freed allocation, often returns whatever bytes happen to be nearby. The program prints a plausible value and the test passes. Miri tracks every allocation, including its size and whether it is still alive. It checks each pointer access against that record.
Out-of-bounds access
This program 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}");
}Natively, this usually prints a number and exits normally. Under Miri it stops with an error like this (the exact text varies by version):
error: Undefined Behavior: memory access failed: attempting to access 4 bytes, but got alloc1234 which is only 12 bytes from the end of the allocationThree facts in this message matter:
- The access was 4 bytes, the size of an
i32. - The allocation holds 3 × 4 = 12 bytes.
- The read starts at offset 12, so it lies entirely outside the allocation.
Note that p.add(3) alone is allowed, because a pointer one past the end is valid. The read through it is the undefined behavior.
Use-after-free
This program frees an allocation and then reads 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 takes ownership back, and drop frees the memory. The pointer p is now dangling. Miri reports a message of this form:
error: Undefined Behavior: dereferencing pointer failed: alloc1234 has been freed, so this pointer is danglingNewer Miri versions also show where the allocation was created and where it was freed. Those extra notes usually point straight at the fix.
Fixing both
Use a checked accessor when you do not need a raw pointer:
fn main() {
let v = vec![1, 2, 3];
match v.get(3) {
Some(x) => println!("{x}"),
None => println!("index 3 is out of range"),
}
}When you must use a pointer, keep the owner alive for as long as the pointer is used. In the second program, move the drop to after the last read.
Common mistakes
- Treating
ptr.add(n)as the error. Forming a pointer is often legal. The dereference is what Miri rejects. - Assuming the report line is the cause. For use-after-free, the real cause is often the earlier
dropor a scope that ended. - Reading only the first line of the error. The notes after it show the allocation's history.
Exercise
In the Vec example, a colleague changes p.add(3) to p.add(2). Does Miri still report an error? Why?
Show answer
No. Index 2 is the last element, so the 4-byte read lies fully inside the 12-byte allocation, and the allocation is still alive because v has not been dropped.