In Rust, what does undefined behaviour mean for code inside an unsafe block, and why does a passing test not prove that block is correct?
answer
- the compiler's assumptions
- unsafe moves the duty, not the rule
- the Reference keeps the list
- debug and release can disagree
basics
~20 sUndefined behaviour is any operation on the Reference's list, such as a data race or an invalid value. rustc optimises as if it never happens, so a program containing it has no defined meaning, and a passing test proves nothing.
solid answer
~50 sThe Rust Reference lists behaviour that Rust code must never exhibit: data races, accessing dangling or misaligned places, breaking the aliasing rules, mutating immutable bytes, producing an invalid value, calling with the wrong ABI, and a few more. The list applies inside `unsafe` blocks too; `unsafe` only means the programmer, not the compiler, is responsible for avoiding it. Because rustc optimises on the assumption that UB never occurs, a program that commits it is not "slightly wrong" but meaningless: it can print the right answer in a debug build, the wrong one in a release build, or change with the next compiler. A test only shows what one build did on one run. To check, read the safety contract of every unsafe operation, and run the tests under Miri, which interprets the program and stops at the first UB on the paths it executes.
code
rust · 6 linesuse std::mem::MaybeUninit;
fn main() {
let x: u32 = unsafe { MaybeUninit::uninit().assume_init() };
println!("{}", x + 1);
}go deeper
Know that unsafe does not relax the rules, only who checks them, and name three items from the Reference's list: data races, invalid values, breaking aliasing.
Explain that the optimiser assumes UB never happens, which is why a debug build can be right and a release build wrong, and why tests are not evidence.
Describe how you would prove a block free of UB: the Safety contract of each call, a SAFETY comment, and tests run under Miri, plus what Miri cannot see.
Frame UB as a property of every execution and every safe caller, which is why unsafe code must be sound, not merely correct for today's callers.
## What the term means in Rust **Undefined behaviour** (UB) is the name the Rust Reference gives to a set of operations that a Rust program must never perform. The Reference's chapter *Behavior considered undefined* opens by saying that Rust code is incorrect if it exhibits any behaviour on the list, and that this includes code inside `unsafe` blocks and `unsafe` functions. The key sentence is that `unsafe` *only means that avoiding undefined behaviour is on the programmer*; it does not change the fact that the program must never cause it. So `unsafe` is not a mode in which the rules are relaxed. It is a mode in which the compiler stops checking some of them and trusts you instead. ## The list, in outline The Reference's list includes, among others: - **data races** between threads; - **accessing a place that is dangling or based on a misaligned pointer**; - **breaking the pointer aliasing rules**, for example two live `&mut` to the same memory, or a write to memory a live `&T` points to (outside an `UnsafeCell`); - **mutating immutable bytes**, such as those behind a shared reference; - **producing an invalid value**: a `bool` other than 0 or 1, a null or dangling reference, an enum with an impossible discriminant, an integer read from uninitialised memory; - **calling a function with the wrong ABI**, or unwinding out of a frame that does not allow unwinding; - **violating assumptions of the Rust runtime**, and misusing inline assembly or compiler intrinsics. The Reference warns that the list is **not exhaustive**: there is no formal model of what unsafe code may do yet, so more may be undefined, and some items may become defined in future. ## Why "it works" is not evidence rustc and its LLVM back end **optimise on the assumption that UB never happens**. If a `bool` must be 0 or 1, the generated code may index a two-entry table with it; if a `&mut T` is unique, the optimiser may keep a value in a register and never reload it. When the assumption is false, the program's behaviour is not "the obvious thing with a bug" — it is not defined at all. In practice that shows up as: 1. a result that is correct in a debug build and wrong in a release build; 2. a result that changes when an unrelated line is added, because inlining decisions move; 3. a result that changes with a compiler upgrade, with no change to your code; 4. a crash far from the line that caused it. The snippet in this question reads an integer out of `MaybeUninit::uninit()`. rustc warns (`invalid_value`) but compiles it; on our run the debug build printed a large arbitrary number and the release build printed `1`. Neither number means anything, and a test that happened to expect one of them would pass. ## UB and soundness The Reference adds a second duty: unsafe code must ensure that **no safe code calling it can trigger UB**. Code that meets that duty is **sound**; code that a safe caller can misuse into UB is **unsound**, even if no current caller does so. How to design such an API is the subject of the lesson on sound safe abstractions; here the point is only that UB is a property of every possible execution, not of the ones your tests ran. ## How you actually check | Approach | What it gives you | |---|---| | Reading each `unsafe` call's `# Safety` section | the exact preconditions you promised to uphold | | A `// SAFETY:` comment per block | a written argument a reviewer can check | | Running tests under Miri | detection of UB on the paths the tests execute | | Ordinary tests | evidence about behaviour, never about the absence of UB | Miri is an interpreter for Rust's intermediate representation that tracks validity, initialisation, alignment and aliasing. It is run with `cargo +nightly miri test` and stops with "Undefined Behavior:" at the first violation it sees. It only sees the code paths it executes, which is why the safety argument still has to be written down.
- If safe Rust cannot cause undefined behaviour, where does UB in a safe program come from?From unsafe code somewhere underneath it, in your crate or a dependency, that is unsound: it lets a safe caller reach an operation on the Reference's list. The fault is attributed to the unsafe code, not the safe caller, because unsafe code is required to make UB impossible for every safe use. A C function called through FFI that has UB of its own also makes the whole program undefined.
- Is the Reference's list of undefined behaviour final?No. The Reference says the list is not exhaustive and may grow or shrink, because Rust has no formal model of what unsafe code may do yet. The aliasing rules in particular are given as an outline, with the exact rules undetermined. In practice you write unsafe code that satisfies the conservative reading and check it under Miri.
- Says unsafe turns off the rules, so anything inside it is allowed.
- Treats a passing test suite as proof that an unsafe block is fine.
- Thinks undefined behaviour just means an unpredictable value, never a miscompile.
- Believes a debug build shows how the release build will behave.
- Claims safe Rust code can be blamed for UB that unsafe code makes reachable.