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 earlier in the tutorial. You should also know what unsafe, raw pointers, and std::mem::transmute are at a basic level.
Not every undefined behavior (UB) involves a bad pointer. Rust also requires that every value of a type is valid for that type, and that memory is initialized before you read it as a typed value. Violating either rule is UB, even if you never use the value afterward. Miri checks both rules as the program executes.
What makes a value valid
Every type defines a set of bit patterns that are valid for it. The compiler relies on this set when it optimizes. Some examples:
| Type | Valid values | Invalid examples |
|---|---|---|
| `bool` | `0` or `1` | `2`, `3`, `255` |
| `char` | Unicode scalar values (not surrogates, at most `0x10FFFF`) | `0xD800`, `0x110000` |
| `&T`, `&mut T`, `Box<T>` | Non-null, aligned, pointing to a valid `T` | null, dangling, misaligned |
| `enum` | Only the discriminants the enum declares | an unlisted discriminant |
| `NonZeroU32` | Any nonzero `u32` | `0` |
| `fn` pointers | Non-null | null |
| integers, floats | Any initialized bit pattern | uninitialized memory |
The key point is that invalidity is a property of the value, not of how you use it. The moment an invalid value is produced, for example by transmute, by reading through a raw pointer, or by mem::zeroed, the program has UB. You do not have to branch on it, print it, or pass it anywhere.
Invalid values from `transmute`
Here is the example from the plan. A bool must be 0 or 1, but 3u8 is neither.
fn main() {
let b: bool = unsafe { std::mem::transmute(3u8) };
println!("{b}");
}Natively this program may print true, or it may behave strangely, depending on optimization level. Under cargo +nightly miri run, Miri stops at the transmute line with a report similar to this:
error: Undefined Behavior: constructing invalid value: encountered 0x03, but expected a boolean
--> src/main.rs:2:29
|
2 | let b: bool = unsafe { std::mem::transmute(3u8) };
| ^^^^^^^^^^^^^^^^^^^^^^^^ constructing invalid value: encountered 0x03, but expected a booleanThe exact wording varies between Miri versions, but the structure is stable. It names the rule (constructing invalid value), the bytes it found (0x03), and the type it expected (a boolean). The error points at the place where the value is created, not where it is later used. That is useful: you do not have to trace the bad value backwards.
The same check on references
Miri applies the same logic to references and Box. This version creates a null reference:
fn main() {
let r: &u32 = unsafe { std::mem::transmute(0usize) };
let _ = r;
}Miri reports that it encountered a null reference. Note that the program never dereferences r. The reference is invalid at the moment it exists, so Miri rejects it. This surprises people who think "I never read through it, so it is fine."
Uninitialized memory
Memory returned by an allocator, or a freshly declared MaybeUninit, holds uninitialized bytes. These are not "random bytes". They are a distinct state that the compiler may treat as any value, and may treat differently at each use. Reading them as an integer, bool, or reference is UB.
Miri tracks, for every byte of memory, whether it has been initialized. This is called init tracking. It lets Miri catch this program:
use std::mem::MaybeUninit;
fn main() {
let slot = MaybeUninit::<u32>::uninit();
let value = unsafe { slot.assume_init() };
println!("{value}");
}assume_init is your promise that the memory holds a valid, initialized u32. Miri checks that promise. Because nothing was written, it reports an error like constructing invalid value at .<enum-tag>: encountered uninitialized memory, but expected an integer.
Natively this program often prints 0 or some stale value, which looks fine. That is exactly why tests miss this kind of bug.
Deprecated patterns: `mem::uninitialized` and `mem::zeroed`
Older code used std::mem::uninitialized::<T>() to get a T without initializing it. This is almost always UB, because the returned value is an uninitialized T. The function is deprecated, and Miri flags uses of it for types that need initialization.
mem::zeroed is subtler. It is fine for integers and floats, because all zero bytes is a valid value. It is UB for &T, Box<T>, NonZeroU32, and fn pointers, where zero is invalid. Miri reports this the same way as the transmute case: at the point where the value is constructed.
Partial initialization and padding
Initialization is tracked per byte, so partially initialized values are caught too. Consider a struct with padding:
#[repr(C)]
struct Pair {
a: u8,
b: u32,
}
fn main() {
let p = Pair { a: 1, b: 2 };
let bytes: [u8; 8] = unsafe { std::mem::transmute(p) };
println!("{}", bytes[0]);
}Pair has three padding bytes between a and b. Padding is uninitialized. Transmuting the struct into [u8; 8] produces a u8 array in which bytes 1 to 3 are uninitialized, and integers may not hold uninitialized bytes. Miri reports an error saying it encountered uninitialized memory where it expected an integer. This is a common source of bugs when code hashes or serializes structs by viewing them as raw bytes.
The correct pattern with `MaybeUninit`
MaybeUninit<T> is a wrapper that is allowed to hold uninitialized memory. It exists so you can build values in place without ever creating an invalid T. The rule is: write first, then 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}");
}Miri accepts this and prints 7. The write call marks the four bytes as initialized, so assume_init meets its contract.
For arrays and larger buffers, the same rule applies per element. You must initialize every element before calling assume_init on the whole array.
use std::mem::MaybeUninit;
fn main() {
let mut buf: [MaybeUninit<u8>; 4] = [MaybeUninit::uninit(); 4];
for (i, slot) in buf.iter_mut().enumerate() {
slot.write(i as u8 * 10);
}
let bytes: [u8; 4] = unsafe { std::mem::transmute(buf) };
println!("{bytes:?}");
}If you change the loop to stop one element early, Miri reports uninitialized memory in the last byte. This is a good experiment: it shows that Miri checks every byte, not just the first.
Reading these reports efficiently
A few habits make these errors fast to diagnose:
- Read the phrase after
constructing invalid value. It tells you which rule failed: wrong bit pattern, null reference, or uninitialized bytes. - Look at the path in the message, such as
.0or.<enum-tag>. It identifies which field of a larger value is invalid. - Follow the first line of the backtrace in your own code. The error is raised where the value is created, so that line is where the fix belongs.
- Ask whether the bytes were never written, or were written but wrong. The first calls for
MaybeUninitand proper initialization. The second calls for validating input before conversion.
Fixing invalid values
Most invalid-value bugs have a safe replacement that removes the need for unsafe.
- Converting an integer to a
bool: usen != 0, ormatch n { 0 => false, 1 => true, _ => ... }. - Converting an integer to a
char: usechar::from_u32(n), which returnsOption<char>. - Converting an integer to an enum: write a
TryFrom<u8>implementation with amatch. - Making a nonzero integer: use
NonZeroU32::new(n), which returnsOption. - Reading bytes as a struct: use a checked approach such as parsing fields one at a time, rather than transmuting a whole buffer.
Here is the char case done safely:
fn main() {
let n: u32 = 0xD800;
match char::from_u32(n) {
Some(c) => println!("char: {c}"),
None => println!("{n:#x} is not a valid char"),
}
}This prints 0xd800 is not a valid char, and Miri has nothing to report.
Edge cases to know
- Zero-sized and empty types. A value of an uninhabited type such as
!or an empty enum can never exist. Creating one, for example throughMaybeUninit::<!>::uninit().assume_init(), is UB, and Miri reports it. - Uninitialized is fine in
MaybeUninit. Moving or copying aMaybeUninit<u32>that is uninitialized is allowed. Only reading it as au32is not. If Miri reports an error, check whether you calledassume_initor used a typed read too early. - Integer-to-pointer values. Integers made from pointers carry extra provenance information, covered in a later chapter. A clean result for integer values does not say anything about the pointer rules.
- Only executed paths are checked. Miri sees the bad
transmuteonly if the test reaches it. A branch that tests never take stays unchecked.
Exercise
The following program prints 0 natively. Name the kind of undefined behavior Miri reports, the line where it reports it, and a one-line fix.
fn main() {
let x: i32 = unsafe { std::mem::MaybeUninit::<i32>::uninit().assume_init() };
println!("{x}");
}
Show answer
Miri reports uninitialized memory where an integer was expected. It reports it at the assume_init call, because that is where the invalid i32 is created, not at the println!. The fix is to write a value before calling assume_init. For example, use MaybeUninit::<i32>::new(0).assume_init(), or better, replace the whole expression with let x: i32 = 0;.
Exercise
Why does Miri flag let r: &u32 = unsafe { std::mem::transmute(0usize) }; even though r is never dereferenced?
Show answer
A reference must be non-null and aligned the moment it exists, so a null reference is an invalid value. Validity is checked when the value is constructed, not when it is used.