Skip to content
Tutorials Center
My learning

Topics

Lesson 112 of 132 ยท Advanced Rust

MaybeUninit, transmute and Raw Memory

Learn Rust's low-level memory tools: MaybeUninit for uninitialized data, transmute and its rules, ptr::read and write, ManuallyDrop, mem::zeroed and safer alternatives.

Safe Rust never lets you see memory that has not been initialized, and never lets you reinterpret the bits of one type as another. Both rules protect you, but both cost something: sometimes you want to fill a large buffer without first writing zeros into it, or build a value one field at a time, or look at the same bytes as two different types. For those jobs the standard library offers a few sharp tools: MaybeUninit<T>, mem::transmute, ManuallyDrop<T> and the ptr::read/ptr::write functions.

All of them need unsafe, and all of them are easy to get subtly wrong. This lesson explains what each one promises, the exact rules you must uphold, and, just as important, the safe alternative you should reach for first. It assumes you have read Unsafe Rust and Memory Layout and Sizes.

Why uninitialized memory is special

You might think that reading a u32 that was never written just gives you "some number". It does not. In Rust's model, an uninitialized byte is not a number at all, and reading one as an integer is undefined behavior, even if the hardware would happily return a value. The optimizer is allowed to assume it never happens. That is why let x: u32 = unsafe { std::mem::uninitialized() } was removed from the language: there was no way to use it correctly.

MaybeUninit<T> is the replacement. It is a wrapper that says "this memory may or may not hold a valid T yet". The compiler stops assuming anything about its contents, and you take responsibility for the moment it becomes a real T.

stateDiagram-v2
    [*] --> Uninit: "MaybeUninit::uninit()"
    Uninit --> Written: "write(value) or ptr write"
    Written --> Valid: "assume_init()"
    Valid --> [*]: "normal T, dropped as usual"
    Uninit --> Valid: "assume_init() here is UB"

The only legal road from uninitialized to a usable T goes through a write.

MaybeUninit basics

Create an empty slot with uninit, fill it with write, and take the value out with assume_init. The method name is a promise: you are asserting that the memory really holds a valid value.

Rust Write first, then assume_init

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Notice what write avoids. A normal assignment slot = x would drop whatever the old value was, and dropping uninitialized memory would be undefined behavior. MaybeUninit never drops its contents on its own either: if you forget to call assume_init (or assume_init_drop), a String inside it simply leaks.

Building an array element by element

The classic use is an array whose elements come from a function that you do not want to run twice, or that cannot be Copy. [T; N] has no Default for arbitrary T, and [expr; N] needs Copy. With MaybeUninit you create the array of slots, fill each one, and convert at the end.

Rust Filling an array of Strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

There is a trap here. If the loop body can panic halfway through (say, format! could fail, or you call a user function), the already-written strings are never dropped, because MaybeUninit does not drop. That is a leak, which is safe, but unwinding code that then reads the half-built array would not be. In a real library you track how many slots are initialized and drop those in a guard. For many cases the safe std::array::from_fn does exactly the right thing for you:

Rust
let labels: [String; 4] = std::array::from_fn(|i| format!("item-{i}"));

Prefer from_fn whenever it fits. Reach for MaybeUninit only when it does not.

Initializing a struct field by field

Sometimes a large struct is built by C code or by a function that fills it through a pointer. MaybeUninit<Struct> plus as_mut_ptr lets you write each field without ever creating a reference to uninitialized memory. Creating a reference &mut to uninitialized data is itself undefined behavior, so use the raw-borrow syntax &raw mut, which makes a pointer to a field without making a reference.

Rust Writing a struct field by field

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

If you skip a field, assume_init produces an invalid Packet and everything after is undefined behavior. There is no compiler check for this. Treat the list of writes like a constructor you must keep in sync with the struct.

mem::zeroed and when zero is not valid

mem::zeroed::<T>() gives you a T whose bytes are all zero. That is a fine initial value for integers, floats, raw pointers and Option<Box<T>> or Option<&T> (null is the None niche, see Memory Layout). It is undefined behavior for types where zero is not a valid value: references, Box, NonZeroU32, and enums that have no variant numbered 0.

Rust Zero is valid for some types, not others

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

In modern code, Default::default() or a const initializer does the same job safely. Use zeroed mostly for C structs from FFI, where all-zero is the documented starting state.

transmute: reinterpreting bits

mem::transmute::<Src, Dst>(value) takes the bytes of value and treats them as a Dst. The compiler checks one thing: the two types must have the same size. Everything else is on you:

  • Every bit pattern of Src you pass in must be a valid Dst.
  • Both types should have a defined layout (repr(C), repr(transparent) or a primitive); the default repr(Rust) layout can differ between compiler versions.
  • Alignment and lifetimes are not magically fixed.
Rust transmute between same-sized types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Both of those have safe, better versions. Using the safe one means no unsafe, an explicit byte order, and the compiler can still optimize it to the same instruction:

Rust The safe alternatives to transmute

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler checks the size

If the sizes differ, the program does not compile. That is one of the few safety nets transmute has.

Rust Different sizes (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

TEXT
error[E0512]: cannot transmute between types of different sizes, or dependently-sized types
  = note: source type: `u16` (16 bits)
  = note: target type: `u32` (32 bits)

Classic mistakes

These all compile and are all undefined behavior or at best fragile:

Rust
// 1. Invalid values: a bool must be 0 or 1.
let b: bool = unsafe { std::mem::transmute(2_u8) };      // UB

// 2. An enum from an integer with no matching variant.
#[repr(u8)]
enum Color { Red = 0, Green = 1 }
let c: Color = unsafe { std::mem::transmute(9_u8) };      // UB

// 3. Pointers to references of any lifetime you like.
let r: &'static str = unsafe { std::mem::transmute(local_ref) }; // dangling

// 4. Reordering a Vec's internals: Vec<T> layout is not guaranteed.
let v: Vec<u8> = unsafe { std::mem::transmute(some_vec_u32) };   // UB

For the second case, write a TryFrom<u8> that returns an error for unknown numbers. For the fourth, use Vec::from_raw_parts with the real allocation rules, or better, copy. The bytemuck crate (shown here read-only) provides checked casts for plain-old-data types that remove most legitimate needs for transmute.

ManuallyDrop and ptr::read/write

ManuallyDrop<T> wraps a value and suppresses its destructor. You decide if and when it drops, with ManuallyDrop::drop (unsafe) or ManuallyDrop::into_inner. It is the tool for taking a value apart without running Drop on the pieces you moved out.

ptr::read(p) copies the bytes at p into a new value and leaves the original in place, without calling any constructor or destructor. That makes two live copies of something that may own memory, so one of them must never be dropped. ptr::write(p, v) moves v into p without dropping the old contents.

Rust Moving a value out with ptr::read and ManuallyDrop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The output shows that a drops once (through copy, at the end of main), and b drops exactly when we say so. If you had not forgotten a, the destructor would have run twice, a double free for anything that owns heap memory.

ptr::read of a type that is not Copy is a duplication of ownership. Always pair it with mem::forget, ManuallyDrop, or a write back into the source, so exactly one copy is ever dropped.

A checklist before you use these tools

  1. Is there a safe API? Try from_fn, to_bits, from_le_bytes, Default, TryFrom, mem::take, mem::replace and Option::take first.
  2. Write the SAFETY: comment before the code: which invariant makes this valid?
  3. Check validity: does every bit pattern you produce make a legal value of the target type?
  4. Check drop: who drops each value, and exactly once?
  5. Run the code under Miri; it catches uninitialized reads, invalid values and double drops.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is reading a u32 from uninitialized memory undefined behavior even though the CPU would return some bits?

    Uninitialized memory is its own state, not an arbitrary number. Code that reads it as an integer breaks the compiler's assumptions, so anything may happen.
  2. 2. What does MaybeUninit::write do that a normal assignment would not?

    write stores the new value and never drops what was there, which is exactly right when there was no valid value to drop.
  3. 3. What does the compiler check when you call mem::transmute?

    Only the sizes must match, and a mismatch is a compile error. Validity of the bits is your responsibility.
  4. 4. Which is the best replacement for transmuting [u8; 4] to u32?

    The from_*_bytes functions are safe, state the byte order explicitly and compile to the same code.
  5. 5. After let copy = ptr::read(&a) where a owns a heap allocation, what must you do?

    ptr::read duplicates ownership. Dropping both copies would free the same allocation twice.

Summary

  • MaybeUninit<T> represents memory that may not hold a valid T; write with write or a raw pointer, then call assume_init only when everything is initialized.
  • Never create a reference to uninitialized data; use &raw mut to reach fields.
  • mem::zeroed is valid only for types where all-zero bytes is a legal value.
  • transmute checks only the size; the bits you convert must be valid for the target type, so prefer to_bits, from_le_bytes, TryFrom and from_fn.
  • ManuallyDrop, mem::forget and ptr::read/ptr::write let you control who drops what; always make sure each value is dropped exactly once.
  • Check low-level code with Miri and document every unsafe block with a SAFETY: comment.

Next: Inline Assembly and SIMD