Sub topic 12
Uninitialized memory with MaybeUninit
This chapter assumes you can write safe Rust with ownership and borrowing, and that you know raw pointers, unsafe fn and # Safety contracts from earlier chapters. You should also know how to run programs with Cargo. Examples need Rust 1.82 or newer, because they use unsafe extern style conventions and inline const blocks.
Why uninitialized memory is a problem
Sometimes you want memory for a value before you have the value. Examples are filling an array element by element, or letting a C function write into a buffer. Safe Rust forbids reading a variable before it is assigned, so the compiler stops you from making this mistake.
In unsafe code you can make the mistake by accident. The rule is that a value of type T must always be valid for T, even if you never use it. Uninitialized memory holds no particular bits. The compiler is allowed to assume it holds a fixed value or no value, and it may optimize on that assumption. For that reason, producing an uninitialized u32, bool, reference or String as a plain value is undefined behavior (UB). This holds even if you never read it.
std::mem::MaybeUninit<T> is the supported tool. It is a wrapper that tells the compiler: this memory is the size and alignment of T, but it may not contain a valid T yet. The wrapper has no validity requirement, so you can hold it uninitialized without UB.
The lifecycle of a MaybeUninit value
A MaybeUninit<T> moves through a few states. The compiler does not track them. You track them.
The main operations are:
| Method | Safe? | What it does |
|---|---|---|
| `MaybeUninit::uninit()` | Yes | Creates a slot with no valid contents. |
| `MaybeUninit::new(v)` | Yes | Creates an initialized slot. |
| `MaybeUninit::zeroed()` | Yes | Fills the slot with zero bytes. |
| `slot.write(v)` | Yes | Stores `v` without dropping the old contents, and returns `&mut T`. |
| `slot.as_ptr()` / `as_mut_ptr()` | Yes | Gives a raw pointer to the memory. |
| `slot.assume_init()` | No | Takes the value out as a `T`. |
| `slot.assume_init_ref()` / `assume_init_mut()` | No | Borrows the contents as `&T` or `&mut T`. |
| `slot.assume_init_read()` | No | Copies the value out without consuming the slot. |
| `slot.assume_init_drop()` | No | Runs `T`'s destructor in place. |
Everything that says "assume" is unsafe. The word is accurate. You are promising the compiler that the memory holds a valid T.
A first example: writing, then reading
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}");
}write is a safe method because it only stores a value. It never reads the old contents, and it never drops them. That second point matters. If you assigned through a &mut T to uninitialized memory, Rust would drop the old value first and so run a destructor on garbage.
Initializing an array element by element
A common use is building [T; N] when T is not Copy and has no Default. You cannot write [MaybeUninit::uninit(); 3], because that form requires Copy. An inline const block avoids that restriction.
use std::mem::{self, MaybeUninit};
fn make_names() -> [String; 3] {
let mut slots: [MaybeUninit<String>; 3] = [const { MaybeUninit::uninit() }; 3];
for (i, slot) in slots.iter_mut().enumerate() {
slot.write(format!("item-{i}"));
}
// SAFETY: every slot was written in the loop above, and
// `MaybeUninit<String>` has the same layout as `String`.
unsafe { mem::transmute::<[MaybeUninit<String>; 3], [String; 3]>(slots) }
}
fn main() {
let names = make_names();
println!("{names:?}");
}The transmute is sound here because MaybeUninit<T> is guaranteed to have the same size, alignment and ABI as T. It only works for a concrete length like 3, because transmute needs sizes known at compile time. For a generic N, people use ptr::read on a pointer cast, or array::from_fn, which is safe and usually the better choice.
What happens if the loop panics?
Suppose format! panicked on the second iteration. MaybeUninit<String> never runs a destructor, so the slot that was written is leaked. The unwritten slots are never dropped. A leak is safe. Dropping an uninitialized String would not be. This is why the wrapper is the right default: forgetting is the safe failure mode.
The reverse needs care. Once you convert the whole array with assume_init, the compiler will drop every element. If one element was not written, you get a drop of garbage. Always make sure the code path that reaches assume_init has initialized everything.
Filling a Vec's spare capacity
Vec already uses this pattern internally, and it exposes it. spare_capacity_mut returns the unused part of the allocation as &mut [MaybeUninit<T>]. You write into it and then tell the Vec how many elements are now real.
fn squares(n: usize) -> Vec<u64> {
let mut v: Vec<u64> = Vec::with_capacity(n);
for (i, slot) in v.spare_capacity_mut().iter_mut().take(n).enumerate() {
slot.write((i * i) as u64);
}
// SAFETY: capacity is at least `n`, and the first `n` elements
// were initialized by the loop above.
unsafe { v.set_len(n) };
v
}
fn main() {
println!("{:?}", squares(5));
}The contract of set_len has two parts: the new length must not exceed the capacity, and every element below it must be initialized. The comment above states both. For plain integers this saves little, but for large buffers filled by a system call it avoids writing zeros first.
Initializing a struct field by field
Sometimes a struct is built in place. The risk is creating a reference to a field that is not yet initialized, which is itself UB. Use raw pointers to fields instead.
use std::mem::MaybeUninit;
use std::ptr::addr_of_mut;
struct Config {
id: u32,
name: String,
}
fn build() -> Config {
let mut slot = MaybeUninit::<Config>::uninit();
let p = slot.as_mut_ptr();
// SAFETY: `p` is valid and aligned for `Config`. `addr_of_mut!` takes
// each field's address without creating a reference, and `write` does
// not drop the old (uninitialized) contents. Both fields are written
// before `assume_init`.
unsafe {
addr_of_mut!((*p).id).write(9);
addr_of_mut!((*p).name).write(String::from("demo"));
slot.assume_init()
}
}
fn main() {
let c = build();
println!("{} {}", c.id, c.name);
}If Config gained a third field and you forgot to write it, this code would still compile. Nothing checks that every field is covered, so add a comment or a test whenever the struct changes.
Common errors
These mistakes appear again and again in real code.
| Mistake | Why it is wrong |
|---|---|
| Calling `MaybeUninit::uninit().assume_init()` for `u32` or `bool` | The result is an invalid value. Even integers must be initialized, and a `bool` must be 0 or 1. |
| Using `mem::uninitialized()` | It is deprecated because it creates the invalid value immediately. |
| Using `MaybeUninit::zeroed()` for `&T`, `Box<T>`, `NonZeroU32` or `fn` pointers | All-zero bits are not valid for those types. Zeroing is fine only when zero is a valid `T`. |
| Taking `&mut *slot.as_mut_ptr()` before writing | It creates a reference to an invalid value. Write through the raw pointer first. |
| Calling `assume_init` twice on a non-`Copy` `T` using `assume_init_read` | Both copies own the same resource, so it is dropped twice. |
| Reading padding bytes of a struct as `u8` | Padding is uninitialized, so those reads are UB. |
Two of these deserve a note. assume_init_read copies the bits and leaves the slot untouched. For a String that means two owners of one heap buffer, and a double free later. Use it only for Copy types, or when you make sure the original is never used or dropped again.
The padding case surprises many people. A struct like struct S { a: u8, b: u32 } has three unused bytes after a. Copying a struct is fine, but viewing its bytes as &[u8] reads those padding bytes.
Checking with Miri
Miri tracks which bytes are initialized and reports a read of uninitialized memory as an error. Run your tests under it:
cargo +nightly miri testTry changing make_names so the loop stops at two items. Miri will flag the invalid String when the array is converted or dropped. Compare that with a normal run, which may print garbage or appear to work. Passing a normal run tells you very little about uninitialized memory.
Review checklist
When you read or write code with MaybeUninit, check these points:
- Which line initializes the value, and does every path to
assume_initpass through it? - Could a panic or early return happen between partial writes, and does that leak safely?
- Does the code create a
&Tor&mut Tto memory that is not yet initialized? - Is zeroing used only for types where all-zero bits are valid?
- Does the SAFETY comment say what was initialized and how?
Exercise
This function compiles. Explain why it has undefined behavior and how to fix it. fn bad() -> u32 { let slot = std::mem::MaybeUninit::<u32>::uninit(); unsafe { slot.assume_init() } }
Show answer
It calls assumeinit on a slot that was never written, so it produces a u32 with no valid value. That violates the validity rule even if the number is never used, and Miri reports it. Fix it by writing first: declare the slot as mut, call slot.write(0) (or any value), and only then call assumeinit. If you do not need uninitialized memory at all, simply write let x: u32 = 0.
Exercise
In the make_names example, suppose the loop only wrote slots 0 and 1, and the code then called transmute. Which operation causes the problem, and what would be dropped incorrectly?
Show answer
The transmute is the problem. It declares all three elements to be valid Strings, but slot 2 was never written. When the returned array is dropped, Rust runs String's destructor on slot 2's uninitialized bytes, which can free an invalid pointer. The initialization claim in the SAFETY comment would be false.