Sub topic 7
Catching invalid values and uninitialized memory
This chapter assumes you can run cargo miri test and read a basic Miri report, as covered in earlier chapters. You should also know what unsafe allows and what a raw pointer is.
Why some values are invalid
Every Rust type has a set of bit patterns that count as valid values. A bool must be 0 or 1. A &T must be non-null and aligned. A char must be a Unicode scalar value. An enum must hold one of its declared discriminants. The compiler optimizes on these rules. If you create a value outside the set, you have undefined behavior (UB), even if you never use the value.
Miri checks validity when a value is created, copied, or passed. It does not wait until the program misbehaves.
An invalid `bool`
fn main() {
let b: bool = unsafe { std::mem::transmute(3u8) };
println!("{b}");
}Natively, this probably prints something odd or nothing wrong at all. Under cargo +nightly miri run, Miri stops at the transmute line. Its message says it encountered 3, but expected a boolean. The error points at the creation of the value, not at the println! that later reads it. This is the point of validity checking: the bug is where the bad value is made.
Uninitialized memory
Memory that has not been written holds no defined value. Reading it as an integer, a bool, or a reference is UB. This surprises many people because the bytes physically exist. In Rust's model they are "uninit", a state separate from any number.
The tool for holding such memory is MaybeUninit<T>. It is allowed to be uninitialized. You must write a value before you call assume_init.
use std::mem::MaybeUninit;
fn main() {
let mut slot = MaybeUninit::<u32>::uninit();
slot.write(7);
let value = unsafe { slot.assume_init() };
println!("{value}");
}This program is correct, and Miri runs it cleanly. If you delete the slot.write(7) line, assume_init claims a u32 exists where none does. Miri then reports that it used uninitialized memory where initialized memory was required.
Common mistakes
mem::zeroedon types with non-zero validity. Zeroing a&T,Box<T>, orNonZeroU32creates an invalid value. Miri reports it at the call.transmutebetween types with different validity. Casting integers tobool,char, or enums is the usual case.- Partial initialization. Writing only some fields of a struct, then calling
assume_initon the whole. - Padding bytes. Padding between fields is uninitialized. Reading a struct as raw bytes can expose it.
Fixing these errors
Match the fix to the cause:
| Cause | Fix |
|---|---|
| Invalid integer cast to `bool` or `char` | Use a safe conversion such as `b != 0` or `char::from_u32` |
| `mem::zeroed` or `mem::uninitialized` | Use `MaybeUninit` and write every field before `assume_init` |
| Reading padding | Avoid byte-level views of types with padding, or copy field by field |
Prefer a safe conversion over transmute when one exists. Keep unsafe blocks small, so the invariant you rely on is easy to state next to the code.
Exercise
A function builds a u32 with MaybeUninit::<u32>::uninit() and calls assume_init() without writing to it. Natively, the program prints 0. Will Miri accept it, and why?
Show answer
No. Miri reports UB because assume_init produces a u32 from uninitialized memory. Printing 0 natively is only what that memory happened to hold. Fix it by calling write with a value before assume_init.
Exercise
Why does Miri report transmute::<u8, bool>(3) at the transmute line instead of at a later if b { ... }?
Show answer
Validity is checked when the value is created. An invalid bool is UB at creation, so Miri stops there, even if the value is never branched on.