Sub topic 2
Undefined behavior and why tests can miss it
This chapter assumes you know Rust ownership, borrowing and lifetimes, can run cargo run and cargo test, and have a basic grasp of raw pointers and the unsafe keyword.
What undefined behavior means
Undefined behavior (UB) is any execution that breaks a rule the Rust language assumes is never broken. Once a program has UB, the language makes no promises about it. It may crash, return wrong values, or appear to work.
The compiler is the reason this matters. It optimizes under the assumption that your program has no UB. If it does, those optimizations can produce code that no longer matches your source.
Safe Rust cannot cause UB. Unsafe Rust can, because inside unsafe you promise to uphold the rules yourself.
Common sources of UB in unsafe code
- Reading or writing outside an allocation.
- Using memory after it has been freed.
- Creating an invalid value, such as a
boolthat is not 0 or 1. - Reading uninitialized memory as if it were a real value.
- Breaking aliasing rules, for example by writing through a pointer that a newer
&muthas invalidated. - Data races, meaning unsynchronized accesses to the same memory from several threads, where at least one is a write.
The next chapters cover each of these in detail.
An example that appears to work
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}");
}Run natively, it usually prints a number and exits normally. The read lands in memory the allocator owns, so the operating system does not stop it. A test that ran this code would pass.
The program is still wrong. The value printed is whatever bytes sit after the buffer, and they could change with a different allocator, a different build, or a different compiler version.
Why tests miss UB
A test checks observable behavior: return values, panics, output. UB does not have to change any of these on a given run.
flowchart TDSeveral things hide UB:
- Lucky memory layout. An out-of-bounds read often hits mapped memory, as in the example above.
- Optimizer decisions. The same source may be fine in a debug build and broken in a release build, or the reverse.
- Platform differences. Behavior can change between operating systems, CPUs and allocators.
- Timing. Data races only misbehave when threads interleave in a particular way, which may be rare.
So a green test suite shows that the code behaved acceptably in the runs you made. It does not show that the code has no UB.
What is needed instead
To find UB reliably you need a tool that checks the rules themselves during execution, instead of waiting for a visible symptom. It must track which memory is valid, which pointers may access it, and whether each value is legal. Miri does this, and the next chapter introduces it.
Exercise
The out-of-bounds read in this chapter prints a number and exits normally on most machines. Give two reasons a normal test run does not prove the code is correct.
Show answer
Any two of: the read often lands in memory that is mapped, so nothing crashes; the printed value is whatever bytes happen to follow the buffer and can change with the allocator or build; the optimizer may treat the code differently in other builds or compiler versions; the compiler assumes no UB, so the program has no defined meaning at all. A test only sees the output of one run, not whether a language rule was broken.