Sub topic 2
Undefined behavior and why tests can miss it
This chapter assumes you know Rust ownership, borrowing and lifetimes, can run cargo test, and have used raw pointers and the unsafe keyword at a basic level. Here you learn what undefined behavior (UB) is, which operations cause it, and why a green test suite says little about it. Miri comes later in the tutorial.
What undefined behavior means
Every language defines what programs mean. For some operations, Rust's rules say that the program has no meaning at all. That is undefined behavior. The compiler is allowed to assume that UB never happens, and it generates code on that assumption.
This differs from other kinds of "unspecified" results:
| Term | What the language promises | Example |
|---|---|---|
| Defined behavior | One exact result | `1u8.wrapping_add(255)` is `0` |
| Panic | A controlled stop with unwinding or abort | `v[10]` on a 3-element `Vec` |
| Implementation-defined | A result that depends on the platform, but is consistent | `size_of::<usize>()` |
| Undefined behavior | No promise about the whole program | `*p` on a dangling pointer |
The last row is the dangerous one. UB is not limited to the line that causes it. The compiler can reorder, delete or rewrite code around it, so the symptoms can appear far from the bug, or not at all.
Where UB comes from in Rust
Safe Rust cannot cause UB. The compiler checks ownership, borrowing and bounds, and a panic! is always a defined outcome. If a safe program shows UB, the cause is a bug in an unsafe block or in the compiler.
The unsafe keyword turns off some checks. It does not turn off the rules. In an unsafe block you promise the compiler that you have upheld the rules it can no longer verify. The main ways to break that promise are:
- Dereferencing a pointer that is dangling, null, misaligned, or outside its allocation (including one element past the end).
- Reading memory that has not been initialized as if it held a value.
- Producing an invalid value, such as a
boolthat is not 0 or 1, or an enum with an unknown discriminant. - Breaking aliasing rules, for example writing through a raw pointer after a newer
&muthas made it stale. - Data races, meaning two threads access the same memory without synchronization and at least one access is a write.
- Calling a function with the wrong ABI or unsupported target features, and a few other cases listed in the Rust Reference.
Later chapters take these one at a time. For now, the point is that each of them is a rule about what your program does at run time. The compiler cannot see most of these violations.
Why UB can look fine
Native execution has no reason to notice UB. The CPU does not know about Rust's rules, and the hardware only faults on a narrow set of mistakes, such as touching an unmapped page. Many violations produce ordinary-looking behavior.
Consider a function that searches a slice through a raw pointer. It has an off-by-one bug: the range 0..=v.len() includes one index past the end.
pub fn contains(v: &[u32], target: u32) -> bool {
let p = v.as_ptr();
for i in 0..=v.len() {
// Bug: when i == v.len(), this reads past the end of the slice.
if unsafe { *p.add(i) } == target {
return true;
}
}
false
}
fn main() {
let data = [1u32, 2, 3];
println!("{}", contains(&data, 2));
println!("{}", contains(&data, 9));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn finds_present_value() {
assert!(contains(&[1, 2, 3], 2));
}
#[test]
fn rejects_absent_value() {
assert!(!contains(&[1, 2, 3], 9));
}
}Both tests normally pass, for two separate reasons.
finds_present_valuereturns at index 1. The faulty read at index 3 never executes. UB depends on the path the program actually takes, so a test that avoids the path cannot expose it.rejects_absent_valuedoes execute the out-of-bounds read. The address after the array is usually mapped memory, so the read returns some leftover value. That value is almost never 9, so the function returnsfalseand the assertion holds. The test passes because of luck about what sits next to the array.
Both tests are green and the code is wrong.
The compiler is part of the problem
Because the optimizer assumes UB cannot happen, UB can change what correct-looking code does. A well-known pattern is a null check placed after a dereference:
/// # Safety
/// `p` must be valid for reads.
pub unsafe fn first_or_zero(p: *const u32) -> u32 {
let v = unsafe { *p };
if p.is_null() {
0
} else {
v
}
}
fn main() {
let x = 42u32;
println!("{}", unsafe { first_or_zero(&x) });
}The read *p is only allowed if p is valid, and a valid pointer is not null. An optimizer may therefore conclude that p.is_null() is always false and remove the branch. With a valid pointer the function behaves as intended. With a null pointer, the code you wrote to handle that case may no longer exist in the compiled program. The behavior can differ between debug and release builds, between compiler versions, and between targets.
That last point matters for maintenance. A program with UB that works today is not safe. It means the compiler has not yet exploited the bug. A compiler upgrade, a changed inlining decision or a new optimization can turn it into a crash or silently wrong output.
Why ordinary tests are weak against UB
Putting the two examples together gives the general reasons.
- Tests only observe outputs. An assertion checks a return value or a side effect. Most UB does not alter either one on the machine you test on.
- Tests cover paths, not rules. A violation on an unexecuted path is invisible. Unsafe code often has rarely taken branches, such as growth, error handling or empty inputs.
- Results depend on the environment. The allocator, stack layout, optimization level, CPU and thread timing all affect whether a bad access hits mapped memory or corrupts something.
- Data races are timing dependent. A race can succeed a million times in a row. Running the test again proves little.
- Debug and release can disagree.
cargo testbuilds without optimizations by default. Many UB-dependent miscompilations appear only with optimizations on. - Failures can be delayed. Memory corruption often shows up as a crash far away from the bad write, long after the test has finished.
Tools exist to close part of this gap. Sanitizers such as AddressSanitizer instrument native code and catch some memory errors. An interpreter that tracks every allocation, pointer and thread, and checks Rust's rules at each step, can catch more of the rule violations listed above, including aliasing errors that native tools mostly miss. Miri is such an interpreter, and the next chapters introduce it.
A practical habit
When you write an unsafe block, write down the condition that makes it valid, usually as a // SAFETY: comment, and as a # Safety section on unsafe fn documentation. For example, "p points to at least len initialized u32 values and is not mutated while this slice exists." That sentence is the contract you are checking when you review the code or run a tool against it. If you cannot state the condition, the block probably has a bug.
Exercise
In the contains example, the test finds_present_value passes. Why does that test say nothing about the off-by-one bug, and what is the minimum change to the function that removes the UB?
Show answer
The test finds the target at index 1 and returns before the loop reaches index v.len(), so the out-of-bounds read never runs. UB depends on executed operations, and this one is not executed. Changing the range from 0..=v.len() to 0..v.len() removes the bad read. Better still, replace the raw pointer loop with v.iter().any(|&x| x == target), which needs no unsafe.
Exercise
A colleague says, "Our unsafe code has been in production for a year with no crashes, so it has no undefined behavior." Give two reasons this conclusion does not follow.
Show answer
Any two of these: UB often has no visible symptom on a given platform, such as an out-of-bounds read that lands in mapped memory. Tests and production traffic only exercise some code paths, and the UB may sit on an unexecuted one. The compiler may not have exploited the bug yet, and a new compiler version or optimization setting can change the result. Data races depend on timing and can stay hidden for a long time.