Sub topic 6
Validity, alignment, and aliasing rules you must uphold
This chapter assumes you know ownership, borrowing, and lifetimes in safe Rust. It also assumes you have met raw pointers and unsafe functions earlier in this tutorial. It covers the three families of rules that unsafe code can break without any compiler warning.
Three rules the compiler stops checking
Inside an unsafe block, the borrow checker and type checker still run. What changes is that you take over some promises the compiler normally enforces. Most of those promises fall into three groups:
- Validity: every value must hold a bit pattern that is allowed for its type.
- Alignment: every pointer you read or write through must be aligned for the type it points to.
- Aliasing: references must obey the shared-xor-mutable rule, even when you made them from raw pointers.
Breaking any of these is undefined behavior (UB). The program may still seem to work. It may then fail after a compiler upgrade or when optimizations change. You need to know these rules precisely, because the compiler optimizes as if you never break them.
Validity: which bit patterns are allowed
A type has a set of valid bit patterns. Producing a value outside that set is UB at the moment the value is created. Using it later is not required. Copying it, passing it to a function, or returning it is enough.
| Type | Requirement for a valid value |
|---|---|
| `bool` | The byte is exactly 0 or 1. |
| `char` | A Unicode scalar value: at most `0x10FFFF` and not in the surrogate range `0xD800` to `0xDFFF`. |
| `&T`, `&mut T`, `Box<T>` | Non-null, aligned, and pointing to memory that holds a valid `T`. |
| `fn` pointers | Non-null. |
| `NonZeroU32` and similar | Never zero. |
| Enums | The discriminant matches one of the declared variants. |
| Integers and floats | Any bit pattern, but the memory must be initialized. |
The last row matters most. Reading uninitialized memory as an integer is UB, even though every integer bit pattern is valid. The reason is that uninitialized memory is not a bit pattern at all. The compiler treats it as a separate state. The chapter on MaybeUninit returns to this.
The most common way to break validity is std::mem::transmute, which reinterprets bits. Transmuting the byte 2 to bool is UB. Prefer conversions that check the input:
fn main() {
let byte: u8 = 2;
// Checked conversions: no unsafe, no UB.
let flag = byte != 0;
let bad_char = char::from_u32(0xD800);
let good_char = char::from_u32(0x41);
println!("{flag} {bad_char:?} {good_char:?}");
}char::from_u32 returns None for a surrogate, so no invalid char is ever built. When a safe checked conversion exists, use it. Reach for transmute only when you can prove the input is in range, and write that proof in a SAFETY comment.
Validity versus safety invariants
Some types carry rules that the language does not enforce but the library does. str must contain valid UTF-8, and Vec<T> must keep len <= capacity. These are safety invariants. Breaking one is not UB at the instant it happens. It is a bug that makes later safe code unsound, because safe methods such as str::chars assume the invariant. In practice, treat both kinds of rule as mandatory. Make a str from non-UTF-8 bytes and later code may misbehave in ways you cannot predict.
Alignment: where a value may live
Every type has an alignment, a number of bytes (always a power of two) that its address must be a multiple of. u8 has alignment 1. u32 usually has alignment 4. Dereferencing a pointer that is not aligned for its type is UB, even on hardware that tolerates unaligned loads. The optimizer may assume aligned access and generate instructions that fault or read the wrong bytes.
If a pointer may be unaligned, use read_unaligned and write_unaligned. They copy the bytes without assuming alignment:
use std::mem::{align_of, size_of};
fn main() {
let bytes: [u8; 8] = [1, 0, 0, 0, 2, 0, 0, 0];
// SAFETY: offset 1 is inside the 8-byte array.
let p = unsafe { bytes.as_ptr().add(1) } as *const u32;
// SAFETY: bytes 1..5 are in bounds and initialized. `read_unaligned`
// does not require `p` to be aligned for u32.
let v = unsafe { p.read_unaligned() };
println!("align {} size {}", align_of::<u32>(), size_of::<u32>());
println!("{}", v == u32::from_ne_bytes([0, 0, 0, 2]));
}The program prints true. Writing *p instead of p.read_unaligned() would be UB whenever p is not a multiple of 4. A [u8; 8] array only guarantees alignment 1, so you cannot assume that.
Packed structs
#[repr(packed)] removes padding, so fields may sit at unaligned addresses. Taking a normal reference such as &h.len to such a field is an error for this reason. A reference must be aligned. Use the raw borrow syntax instead:
#[repr(C, packed)]
struct Header {
tag: u8,
len: u32,
}
fn main() {
let h = Header { tag: 1, len: 300 };
let tag = h.tag; // copying a field by value is always fine
let p = &raw const h.len; // a raw pointer, not a reference
// SAFETY: `p` points to the live, initialized field `h.len`.
// The field may be unaligned, so we use `read_unaligned`.
let len = unsafe { p.read_unaligned() };
println!("{tag} {len}");
}&raw const and &raw mut create a raw pointer directly from a place, with no intermediate reference. They are also the right tool for pointing at uninitialized fields or at statics.
Aliasing: what references promise
A reference is a stronger statement than a raw pointer. The rules in short:
- A
&Tpromises that nobody mutates the target while the reference is live, unless the target is inside anUnsafeCell(as withCell,RefCell, andMutex). - A
&mut Tpromises that it is the only way to reach the target while it is live. No other reference or pointer derived from elsewhere may read or write it.
The compiler uses these promises. It may keep a value from behind a &T in a register across a call, because it believes no one changed it. It may reorder writes through different &mut references. If you break the promise, the generated code can disagree with what you wrote.
Raw pointers carry no such promise. Two raw pointers to the same value are fine:
fn main() {
let mut x = 10;
let a = &raw mut x;
let b = a; // a second raw pointer to the same place
// SAFETY: both pointers come from `x`, which is live and aligned.
// No references to `x` exist while we write through them.
unsafe {
*a += 1;
*b += 1;
}
println!("{x}");
}The output is 12. The trouble starts when you turn a raw pointer into a reference with &mut *ptr. At that moment you make the exclusivity promise. If you make two &mut references from the same pointer and use both, the first one is invalidated by the second, and using it afterward is UB. Keeping each reference's lifetime short avoids this. Create it, use it, and let it end before you make the next.
What is still undecided
Rust has no final, official aliasing model. Two experimental models, Stacked Borrows and Tree Borrows, are implemented in Miri and agree on the clear cases. They disagree on some edge cases. The safe rule is to follow the conservative reading. Make references from a pointer only when you hold exclusive access, and do not mix reference and pointer use of the same memory in interleaved ways.
Dangling and unbounded references
A reference must also point to live memory. &*ptr can produce a reference with any lifetime you like, because the compiler cannot link it to the data's real lifetime. If the data is freed while that reference exists, you have a dangling reference. This is UB even if you never read through it. Prefer to keep the value as a raw pointer until you actually need a reference.
Putting the rules into a review habit
When you write a SAFETY comment, name which rule you are upholding. A useful comment answers these questions:
- Is the pointer non-null, aligned, and in bounds for the type?
- Does the memory hold a fully initialized, valid value of that type?
- Is the memory alive for as long as any reference made from it?
- Could any other pointer or reference read or write it while a
&mutexists, or write it while a&exists?
If you cannot answer one of these in a sentence, the code is not ready. Either restructure it, for example by using read_unaligned instead of a reference, or leave the operation to a safe API from the standard library. The next chapter uses these checks to wrap unsafe code in a safe interface, and a later chapter shows how Miri detects violations of all three rule groups.
Exercise
A colleague writes let r: &mut u32 = unsafe { &mut *p }; where p: *mut u32 is a valid pointer to an initialized u32, but p came from byte offset 1 of a [u8; 8] array. Which rule is broken, and what is the fix if the goal is only to read the value?
Show answer
Alignment. A &mut u32 must be aligned to 4 bytes, and a pointer at offset 1 of a byte array is not guaranteed to be. Creating the reference is UB at that moment. To read the value, keep the pointer raw and call p.read_unaligned(), which has no alignment requirement.
Exercise
Why is let b: bool = unsafe { std::mem::transmute(2u8) }; UB even if the program never prints or branches on b?
Show answer
A bool is valid only if its byte is 0 or 1. Validity is checked when the value is produced, not when it is used. The compiler may assume every bool is 0 or 1, so producing a 2 breaks that assumption. A safe alternative is byte != 0.
Exercise
You have a *mut i32 named p. You write let a = unsafe { &mut *p }; let b = unsafe { &mut *p }; *a += 1; *b += 1;. What goes wrong, and how would you restructure it?
Show answer
Creating b while a is still used later breaks the exclusivity promise of &mut, so the use of a is UB. Make the references one at a time so the first ends before the second starts, or use *p += 1; twice through the raw pointer without creating references.