skip to content

Undefined Behaviour and Miri

Breaking an aliasing rule or creating an invalid value is undefined behaviour even if the program seems to work. Interviewers ask for examples and how Miri catches them.

on this pageshow

questions

5

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?

level: juniorimportance: should knowfreq 45%

answer

  1. the compiler's assumptions
  2. unsafe moves the duty, not the rule
  3. the Reference keeps the list
  4. debug and release can disagree

basics

~20 s

Undefined 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 s

The 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 lines
rust
use std::mem::MaybeUninit;

fn main() {
    let x: u32 = unsafe { MaybeUninit::uninit().assume_init() };
    println!("{}", x + 1);
}

go deeper

for a junior

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.

for a middle

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.

for a senior

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.

for a principal

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.
open as a page

What does running `cargo miri test` catch in a Rust crate's unsafe code, and what can Miri not tell you?

level: middleimportance: should knowfreq 40%

basics

~20 s

Miri interprets the crate's tests and stops at undefined behaviour it observes: invalid or uninitialised values, out-of-bounds or misaligned accesses, aliasing violations, data races, leaks. It sees only executed paths and cannot run most foreign calls.

open as a page

A Rust parser transmutes wire bytes into a `#[repr(C)]` header with a `bool` field; why is a byte of 2 undefined behaviour?

level: middleimportance: should knowfreq 42%

basics

~20 s

A bool may only hold 0 or 1, and producing any other value is immediate undefined behaviour. mem::transmute checks only that the sizes match, so the parser must validate the byte and build the header field by field.

open as a page

In Rust, why is `mem::zeroed::<&u32>()` undefined behaviour, and how does `MaybeUninit<T>` let unsafe code defer initialisation soundly?

level: seniorimportance: should knowfreq 35%

basics

~20 s

A reference must be non-null, so an all-zero &u32 is an invalid value the moment it exists. MaybeUninit<T> holds bytes that need not be valid; you write the value and call assume_init only once it is fully initialised.

open as a page

A Rust optimisation creates two `&mut [u8; 8]` to one buffer from a raw pointer and the output is correct; why is it still undefined behaviour?

level: seniorimportance: should knowfreq 40%

basics

~20 s

A live &mut T must be the only reference to its memory. Using the first &mut after the second one was created and written breaks the aliasing rules, which is UB however the output looks; Miri reports it.

open as a page