Sub topic 2
What undefined behavior means
This chapter assumes you know safe Rust ownership, borrowing, and references, and that you can build and run a program with Cargo. It explains the term that the rest of unsafe Rust depends on: undefined behavior.
The definition
Undefined behavior (UB) means the language places no requirements on what your program does once a rule is broken. The program may crash, print a wrong answer, or appear to work. It may also behave differently after you change the optimization level or the compiler version.
UB is not a runtime error like a panic. A panic is defined: it unwinds the stack or aborts, and you can predict it. UB is a broken promise between you and the compiler, and the compiler gives no guarantee about the result.
Why the compiler can ignore your mistakes
The optimizer assumes your program never triggers UB, and it rewrites code on that assumption. If your code does break a rule, those rewrites can produce results that look unrelated to the mistake.
For example, the compiler may assume a &T always points to valid, initialized memory. It may then skip a check or reorder a read based on that assumption. The bug can show up far from the line that caused it.
What unsafe changes
In safe Rust, the compiler checks the rules that prevent UB. Inside an unsafe block, it still checks types, borrowing of ordinary references, and lifetimes. The unsafe keyword only unlocks a few extra operations. For those operations, you must check the rules yourself.
Safe Rust cannot cause UB, assuming the unsafe code underneath it is correct. That guarantee is why correctness of unsafe code matters so much.
Common sources of UB
| Rule broken | Example |
|---|---|
| Dereferencing an invalid pointer | Null, dangling, or out of bounds |
| Misaligned access | Reading a `u32` from an address that is not a multiple of 4 |
| Invalid values | A `bool` that is neither 0 nor 1, or a null reference |
| Aliasing violations | A `&mut T` that overlaps another live reference to the same data |
| Data races | Two threads access the same memory, and at least one writes |
| Uninitialized reads | Treating uninitialized memory as an integer |
The later chapters on validity rules and MaybeUninit cover these in detail.
A small example
The following program stays inside the rules. It reads from a raw pointer, and the index is within the array.
fn main() {
let values = [10u32, 20, 30];
let p = values.as_ptr();
// SAFETY: index 2 is inside the array, which has length 3.
let ok = unsafe { *p.add(2) };
println!("{ok}");
// Reading `*p.add(3)` would be UB: it is one past the end.
}Changing the index to 3 would still compile. It might even print a plausible number. That is why UB is dangerous: the compiler cannot tell you about it, and a test passing does not prove it is absent.
Reasoning about it
When you write unsafe code, ask one question for each unsafe operation: which rule could this break, and why does it hold here? Writing the answer in a // SAFETY: comment forces you to find the rule and check it. Later chapters build on this habit with safety contracts and Miri.
Exercise
A colleague says their unsafe code is fine because it has run in production for a year without crashing. Why is that not enough, and what does it show?
Show answer
UB places no requirements on the result, so working output is one of the allowed outcomes. A year without a crash shows only that this compiler and target happened to produce harmless code. It does not show the rules are upheld. A later compiler or optimization change could break the program. The code needs a reasoned argument, such as SAFETY comments, and a tool like Miri to check it.