Undefined Behaviour in Unsafe Rust and How Miri Detects It
Safe Rust has no undefined behavior, but unsafe blocks can. See what counts as UB in unsafe Rust and how the Miri interpreter reports each kind.

Rust's headline promise is that safe code cannot cause undefined behavior. That promise ends at the keyword unsafe. Inside an unsafe block, the compiler trusts you to uphold rules it cannot check, and breaking one gives you the same kind of undefined behavior C has, with the same consequences: the optimizer assumes it never happens. This post lists what counts as undefined behavior in Rust, shows three small examples, and explains how Miri, the interpreter that ships as a rustup component, turns each into a clear error message. It assumes Rust 1.85 for the language and a recent nightly toolchain for Miri.
Where undefined behavior can come from
Rust has a short, written list. The Rust Reference chapter "Behavior considered undefined" is the authority, and the standard library's unsafe function docs state the extra conditions for each function. The categories you meet in practice are these.
Data races. Two threads access the same memory, at least one writes, and neither access is atomic or synchronized.
Invalid memory access. Dereferencing a dangling, null or out-of-bounds pointer, or a pointer that is not aligned for the type. Reading memory through a pointer whose allocation has been freed is in this group.
Breaking the aliasing rules. A
&mut Tmust be the only live way to reach the memory it points to, and a&Tpromises the data will not change while it is alive, except insideUnsafeCell. Raw pointers are exempt from the rules, but converting them into references brings the rules back.Producing an invalid value. A
boolthat is neither 0 nor 1, acharthat is not a Unicode scalar value, an enum with an out-of-range discriminant, a reference that is null or dangling, a!value, or an integer, float or pointer read from uninitialized memory.Calling a function with the wrong ABI, or unwinding across an FFI boundary that does not allow it.
Mutating immutable data, such as a
staticthat is notmutor aconstallocation.
The list is narrower than C's in one respect. Signed integer overflow is not undefined: in debug builds it panics, and in release builds it wraps unless you ask otherwise with overflow-checks. Null checks cannot be deleted by assuming a dereference happened. And array indexing is bounds-checked in safe code, so out-of-bounds access needs a raw pointer or get_unchecked.
What Miri is
Miri is an interpreter for Rust's mid-level intermediate representation. Instead of running machine code, it executes your program one MIR step at a time and checks each operation against the rules above. Because it knows every allocation, every pointer's provenance and every reference's permissions, it can detect violations that the hardware would never notice.
Install it and run it with the nightly toolchain:
rustup +nightly component add miri
cargo +nightly miri run
cargo +nightly miri testTwo properties set the expectations. Miri is slow, often 10 to 100 times slower than native, so you run it on tests and small programs rather than in production. And it checks only the code paths that execute, so a clean run proves those paths are free of the errors it knows, not that the whole program is correct. It is also precise about what it knows: it does not model every platform detail, and it cannot call arbitrary foreign functions, so tests that depend on a C library may need to be skipped.
Example 1: an out-of-bounds read
fn main() {
let v = vec![1u32, 2, 3];
let p = v.as_ptr();
let x = unsafe { *p.add(3) }; // one past the end, then read
println!("{x}");
}Natively this typically prints whatever the allocator left after the vector, and it may print different digits every time. Under Miri it stops with an error that names the allocation and the offset:
error: Undefined Behavior: memory access failed: attempting to access 4 bytes, but got alloc1134+0xc which is at or beyond the end of the allocation of size 12 bytes
--> oob.rs:4:30
|
4 | let x = unsafe { *p.add(3) }; // one past the end, then read
| ^^^^^^^^^ Undefined Behavior occurred hereThe three elements occupy 12 bytes, so the pointer at offset 0xc (12) is exactly one past the end. Forming that pointer with add is allowed. Reading through it is not. The allocation number (alloc1134 here) and the exact wording change between Miri versions, so read the message for its structure, which says what was attempted, what the pointer was and what the allocation is.
Example 2: an invalid value
fn main() {
let byte: u8 = 2;
let flag: bool = unsafe { std::mem::transmute(byte) };
if flag {
println!("true");
} else {
println!("false");
}
}A bool must be 0 or 1. The compiler is allowed to assume that, and may generate code in which flag is neither true nor false. Natively the program prints one of the two lines. Miri catches the problem at the moment the invalid value is created:
error: Undefined Behavior: constructing invalid value: encountered 0x02, but expected a boolean
--> invalid.rs:3:51
|
3 | let flag: bool = unsafe { std::mem::transmute(byte) };
| ^^^^ constructing invalid value: encountered 0x02, but expected a booleanNote that the error is on the transmute, not on the if. The validity rule applies when a value of that type is produced, which is the same principle as in C, where an uninitialized or trap value may not be read. The safe alternatives are byte != 0 or u8::try_from-style checks that map the number into a bool explicitly, or std::mem::transmute only on types for which every bit pattern is valid, such as [u8; 4] to u32.
Example 3: breaking the aliasing rules
The subtlest class is aliasing, because the code looks harmless and the hardware agrees.
fn main() {
let mut x = 10;
let a = &mut x as *mut i32;
let r = unsafe { &mut *a }; // a unique reference derived from a
let b = unsafe { &mut *a }; // a second one, invalidating r
*b = 20;
*r = 30; // use of the old reference
println!("{x}");
}Natively this prints 30 and nothing looks wrong. Under Miri's default model, called Stacked Borrows, r was invalidated when b was created from the same raw pointer, so using r is a violation:
error: Undefined Behavior: attempting a write access using <2937> at alloc1170[0x0], but that tag does not exist in the borrow stack for this locationThe full message continues with notes that say where each tag was created and where it was invalidated, which is usually enough to find the offending line. Miri also offers an alternative model, Tree Borrows, selected with MIRIFLAGS="-Zmiri-tree-borrows". It accepts some patterns that Stacked Borrows rejects, and its authors present it as the more permissive candidate for the final rules. Because the formal aliasing rules are not settled, the safest policy is to run Miri under both and fix anything either flags.
The practical rule that avoids the problem: derive each reference from the raw pointer right before you use it, use it, and do not keep it across another derivation. In the example, using r before creating b would be fine.
Other things Miri checks
Beyond these three it reports use after free and double free, reads of uninitialized memory (using uninitialized data, but this operation requires initialized memory), misaligned pointer dereferences, data races in tests that spawn threads, calls to functions with the wrong signature, and memory leaks at exit unless you pass -Zmiri-ignore-leaks. It can also run a test many times with different thread schedules and random seeds, with -Zmiri-many-seeds, which helps expose races that depend on timing. Setting -Zmiri-strict-provenance makes it reject code that relies on integer-to-pointer casts getting provenance back.
Putting it in your workflow
Run cargo +nightly miri test in CI on any crate with unsafe, in a job that is allowed to take a few minutes. Write small tests that exercise each unsafe function with edge inputs: empty slices, zero-length allocations, the largest valid index, and values just outside a range. Keep unsafe blocks small and attach a // SAFETY: comment that states the condition the caller must meet, and enable Clippy's undocumented_unsafe_blocks lint so a missing comment fails the build. The combination of narrow unsafe, comments that state the invariant and Miri on the tests is what the standard library itself uses.
What Miri cannot promise
Miri tells you the program is free of the errors it checks, on the paths it ran, under the aliasing model it uses. It does not model hardware behavior, it cannot execute inline assembly or most foreign calls, and the aliasing rules are still being specified, so a program Miri accepts today could be rejected if the rules tighten. Use it as strong evidence and keep the unsafe surface as small as you can.


