Sub topic 12
Uninitialized memory with MaybeUninit
This chapter assumes you know ownership and borrowing, raw pointers, and the rule that an unsafe function documents its safety contract. You should also know that creating an invalid value is undefined behavior (UB).
Why uninitialized memory is a problem
Sometimes you need a buffer before you have values to put in it. Examples are filling an array element by element, or letting a C function write into memory you pass it.
Safe Rust forbids reading a variable before it is set. In unsafe code the tempting shortcut is std::mem::zeroed() or a raw allocation that you treat as a typed value. Both can be UB. The compiler assumes every value of type T is valid for T. A bool must be 0 or 1. A &T must be non-null and point to a live value. Memory that is uninitialized or holds the wrong bit pattern breaks those rules the moment you treat it as a T.
std::mem::MaybeUninit<T> solves this. It is a wrapper that holds space for a T and promises nothing about the contents. Because the compiler makes no validity assumptions about a MaybeUninit<T>, you can safely hold one in any state.
The basic workflow
The workflow has three steps: create the slot, write a value, then assert initialization.
use std::mem::MaybeUninit;
fn main() {
let mut slot = MaybeUninit::<u32>::uninit();
slot.write(42);
// SAFETY: `slot` was fully initialized by the write above.
let value = unsafe { slot.assume_init() };
println!("{value}");
}uninit() and write() are safe. Writing to a MaybeUninit never reads the old contents and never drops them, so it is always sound. assume_init() is unsafe because you are telling the compiler "this is now a valid T." The compiler cannot check that claim, so the SAFETY comment must say why it holds.
Common errors
- Calling
assume_inittoo early. If any byte that matters is still uninitialized, the result is UB, even if you never print it. - Using
mem::uninitialized()ormem::zeroed()for types with validity rules.zeroedis wrong for references,NonNull,Box, and many enums. UseMaybeUninitinstead. - Forgetting drop behavior.
MaybeUninit<T>never drops its contents. If you initialize aStringinside one and never callassume_init,assume_init_drop, or otherwise take it out, the string leaks. Leaking is safe but usually unwanted. - Creating a reference to uninitialized data. A
&u32that points to uninitialized memory is already invalid. Useas_mut_ptr()and write through the raw pointer.
Initializing arrays piece by piece
The next example fills an array of MaybeUninit values one at a time. It then converts the whole array at once.
use std::mem::MaybeUninit;
fn main() {
let mut items: [MaybeUninit<u32>; 4] = [MaybeUninit::uninit(); 4];
for (i, item) in items.iter_mut().enumerate() {
item.write((i as u32) * 10);
}
// SAFETY: every element was written in the loop above, and
// `MaybeUninit<u32>` has the same layout as `u32`.
let items: [u32; 4] = unsafe { std::mem::transmute(items) };
println!("{items:?}");
}An array of MaybeUninit<T> is itself always valid, so building one needs no unsafe. The unsafe step is the conversion, and its justification is that the loop covered every index. If the loop had a break or an early continue, the claim would fail.
Exercise
A function creates let mut s = MaybeUninit::<String>::uninit();, writes String::from("hi") into it, and returns without calling assume_init or assume_init_drop. Is this undefined behavior? What happens to the string?
Show answer
It is not undefined behavior. Writing to a MaybeUninit is safe, and the slot is never read as a String. But MaybeUninit does not run the destructor of its contents, so the String's heap allocation is leaked. To avoid the leak, call unsafe { s.assume_init_drop() } (or assume_init() and let the result drop).
Exercise
Why is let x: bool = unsafe { std::mem::zeroed() }; fine, but let r: &u32 = unsafe { std::mem::zeroed() }; is undefined behavior?
Show answer
All-zero bits are a valid bool (false). All-zero bits for a reference mean a null reference, which violates the rule that references are never null. Using MaybeUninit<&u32> and only calling assume_init after writing a real reference avoids the problem.