skip to content

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%

answer

  1. all-zero is not always valid
  2. the initialisation invariant
  3. a wrapper with no validity rule
  4. write, then assume_init
  5. it never drops its contents

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.

solid answer

~40 s

The compiler assumes every variable of type `T` holds a valid `T`; the `MaybeUninit` docs call this the initialisation invariant. `mem::zeroed::<T>()` is only sound when all-zero bytes are a valid `T`: fine for integers, UB for references, `fn` pointers and `NonZero` types. `mem::uninitialized` is worse and deprecated since 1.39, because uninitialised bytes are invalid even for integers. `MaybeUninit<T>` is a wrapper the compiler makes no validity assumption about, so `MaybeUninit::uninit()` is always safe to create. You fill it with `MaybeUninit::write` or through `as_mut_ptr`, then call the unsafe `assume_init` exactly when every byte that matters is initialised. It never runs `T`'s destructor itself, so a partly built value leaks rather than drops garbage.

code

rust · 6 lines
rust
fn main() {
    let n: u32 = unsafe { std::mem::zeroed() }; // fine: all-zero is a valid u32
    println!("{n}");
    let r: &u32 = unsafe { std::mem::zeroed() }; // UB: a null reference
    println!("{r}");
}

go deeper

for a junior

Recall that some types forbid certain bit patterns, so zeros or uninitialised memory can be invalid even before anyone uses the value.

for a middle

Explain why mem::zeroed is fine for integers but UB for references, and the three steps of MaybeUninit: uninit, write, assume_init.

for a senior

Handle the details: assume_init is the single point of truth, MaybeUninit never drops its contents, write instead of assignment, and verify with Miri.

for a principal

Ban mem::uninitialized and question every mem::zeroed in review; MaybeUninit with a short safety argument is the default for deferred initialisation.

## The initialisation invariant The `MaybeUninit` documentation states the rule plainly: the compiler, in general, **assumes that a variable is properly initialised, or valid, according to the requirements of its type**, and this invariant must always be upheld, even in unsafe code. The Reference lists producing an invalid value as undefined behaviour, and its validity rules include: - a **reference or `Box<T>`** must be aligned and non-null and must not dangle; - a **`fn` pointer** must be non-null; - a **`bool`** must be 0 or 1; - an **integer, float or raw pointer** must be initialised. The compiler exploits these for optimisation, for example storing `None` of an `Option<&u32>` as the null pointer. ## `mem::zeroed` and `mem::uninitialized` | Function | What it produces | Sound for | |---|---|---| | `std::mem::zeroed::<T>()` | a `T` whose bytes are all zero | types where all-zero is valid: integers, floats, raw pointers, `Option<&T>` | | `std::mem::uninitialized::<T>()` | a `T` that claims to be initialised but is not | nearly nothing; deprecated since 1.39 | | `MaybeUninit::<T>::uninit()` | a `MaybeUninit<T>` with no initialised bytes | every `T` | | `MaybeUninit::<T>::zeroed()` | a `MaybeUninit<T>` whose bytes are zero | every `T` (the validity question moves to `assume_init`) | `mem::zeroed::<&u32>()` produces a null reference, which is **immediate UB whether or not it is ever dereferenced**. rustc warns with the `invalid_value` lint ("references must be non-null"), and the current `mem::zeroed` calls an intrinsic check that panics with *attempted to zero-initialize type `&u32`, which is invalid* and then aborts; its source calls that check best-effort, not a guarantee. `mem::uninitialized` has the same effect as `MaybeUninit::uninit().assume_init()`, and its docs say it is immediate UB on nearly all types, *including integer types*, because uninitialised memory has no fixed value: reading the same byte twice may give different results. ## How `MaybeUninit<T>` works `MaybeUninit<T>` has the same size and alignment as `T`, but the compiler makes **no validity assumption** about its contents. That moves the moment of truth from creation to a single unsafe call: 1. **Create** it with `MaybeUninit::uninit()` (safe) or, for an array, `[const { MaybeUninit::uninit() }; N]`. 2. **Fill** it with `MaybeUninit::write(&mut self, val)`, which stores the value without dropping whatever was there, or through `as_mut_ptr()` for field-by-field and out-pointer initialisation. 3. **Promise** it is initialised with `unsafe { x.assume_init() }`, which returns the `T`. Calling it before the value is fully initialised is immediate UB, exactly as with `mem::uninitialized`. The docs also note `assume_init_ref`, `assume_init_mut` and `assume_init_read` for borrowing or copying out without consuming the wrapper, and `assume_init_drop` for dropping an initialised value in place. ## Drops and partial initialisation - **Dropping a `MaybeUninit<T>` never runs `T`'s drop code.** If you wrote a `String` into it and then let it go out of scope without `assume_init`, the `String` leaks. Leaking is safe; dropping uninitialised garbage would not be. - For an array filled in a loop, a panic halfway through leaks the elements already written. That is safe; a guard that drops the initialised prefix is the tidy refinement. - **Padding bytes need not be initialised** before `assume_init`, as the docs' field-by-field struct example shows; every field must be. - Use `write`, not `*ptr = val`, on uninitialised memory: assignment would first drop the old value, which here is garbage. ## Choosing in practice - A plain integer or `repr(C)` struct of integers for an FFI call: `mem::zeroed` is acceptable, and its docs say it is sometimes useful for FFI. - Any type containing a reference, `Box`, `fn` pointer, `bool`, `char`, `NonZero` or an enum: never zero or skip initialisation; use `MaybeUninit<T>`. - An out-parameter filled by another function, or an array of non-`Copy` values built element by element: `MaybeUninit<T>`, as in the second snippet, which Miri runs clean. Wrapping these patterns into a safe container type, and proving it sound, is the subject of the lesson on sound safe abstractions.

  • Is `mem::zeroed::<Option<&u32>>()` undefined behaviour?
    No. Option of a reference uses the null pointer to represent `None`, so all-zero bytes are a valid `Option<&u32>`, namely `None`. The same zero bytes are invalid for `&u32` itself. Validity is a property of the exact type, which is why `mem::zeroed` needs case-by-case justification.
  • What happens to values written into a `MaybeUninit` if the code panics before `assume_init`?
    They leak. Dropping a `MaybeUninit<T>` never runs `T`'s destructor, so the already-written values are not dropped and their resources are not released. That is memory-safe, because leaking is allowed in Rust; to avoid it, track how many slots are initialised and drop that prefix with `assume_init_drop` from a guard.
  • Why does writing `*slot.as_mut_ptr() = value` risk UB where `slot.write(value)` does not?
    Assignment through a place first drops the old value there. In uninitialised memory the old "value" is garbage, so for a type with a destructor that drop runs on invalid data. `MaybeUninit::write`, like `ptr::write`, stores the new value without dropping the old one.

MaybeUninit<T> is a reserved parking space: the sign says a car will go there, nobody may treat the space as holding a car until one is parked and the sign comes down (assume_init), and if the reservation lapses, nobody tows away whatever car was left in it.

  • Says an all-zero reference is fine as long as it is never dereferenced.
  • Thinks mem::uninitialized is sound for integers because any bit pattern is a valid integer.
  • Believes MaybeUninit drops its contents automatically when it goes out of scope.
  • Calls assume_init before every field has been written.
  • Treats the runtime zero-initialisation panic as a guarantee that catches every misuse.