Sub topic 6
Validity, alignment, and aliasing rules you must uphold
This chapter assumes you know ownership, borrowing, and references in safe Rust. It also assumes you have met raw pointers and unsafe blocks. Inside an unsafe block the compiler stops checking some rules, but the language still requires them. Breaking one is undefined behavior (UB). This chapter covers the three rule families you will break most often.
Validity
Every type has a set of values that count as valid. Producing a value outside that set is UB, even if you never use it.
| Type | Invalid values |
|---|---|
| `bool` | Any byte other than 0 or 1 |
| `char` | Values above `0x10FFFF` and surrogates |
| `&T`, `&mut T`, `Box<T>` | Null, dangling, or misaligned pointers |
| `enum` | A discriminant that no variant uses |
| `!` | Any value at all |
The check applies at the moment the value is created. Casting a byte to bool with transmute is UB if the byte is 2, even when the next line discards it. So test the input first, then convert:
fn byte_to_bool(byte: u8) -> Option<bool> {
if byte > 1 {
return None;
}
// SAFETY: `byte` is 0 or 1, and both are valid `bool` values.
Some(unsafe { std::mem::transmute::<u8, bool>(byte) })
}
fn main() {
println!("{:?} {:?}", byte_to_bool(1), byte_to_bool(2));
}A plain match would be better in real code. The transmute is here only to show the pattern: check, then convert.
Alignment
A type with alignment N must live at an address that is a multiple of N. A u32 needs a multiple of 4. Dereferencing a misaligned pointer is UB. This is true on x86 too, where the hardware tolerates it, because the compiler optimizes on the assumption that pointers are aligned.
Raw pointers may be misaligned. Only reading or writing through them requires alignment. If the data might be misaligned, for example when it comes from a byte buffer, use read_unaligned:
fn main() {
let bytes: [u8; 8] = [1, 0, 0, 0, 0, 0, 0, 2];
// Offset 1 is not a multiple of 4, so this pointer is misaligned for u32.
let p = bytes.as_ptr().wrapping_add(1) as *const u32;
// SAFETY: bytes 1..5 are inside the array and initialized, and
// `read_unaligned` places no alignment requirement on `p`.
let value = unsafe { p.read_unaligned() };
assert_eq!(value, u32::from_ne_bytes([0, 0, 0, 0]));
println!("{value}");
}Calling p.read() here would be UB. You can also create a reference with &*p, but that is UB for the same reason.
Aliasing
The compiler assumes that a &mut T is the only way to reach its data while it is live. It assumes that a &T points to data nobody mutates, except inside UnsafeCell. Breaking either assumption is UB, because the optimizer may cache or reorder reads and writes.
Aliasing rules apply to references, not raw pointers. Two raw pointers to the same memory are fine. Two live &mut references to it are not.
fn main() {
let mut x = 10;
let a = &mut x as *mut i32;
let b = a;
// SAFETY: `a` and `b` are copies of one pointer derived from `x`.
// No references to `x` are live, so there is no aliasing violation.
unsafe {
*a += 1;
*b += 1;
}
println!("{x}");
}The rule that catches people is that creating a reference asserts its guarantees, even if you never use it. Writing let r = &mut *p; while another &mut to the same data is live is already UB.
Habits that keep you inside the rules
- Prefer raw pointers and methods like
ptr.read()andptr.write()over creating temporary references. - Check validity before conversion, not after.
- Use
read_unalignedandwrite_unalignedfor data of unknown alignment. - Derive pointers from a reference or allocation that is still valid. Do not use a pointer after its source is dropped or moved.
- Write the rule you rely on in a
// SAFETY:comment. If you cannot name the rule, you do not yet know the code is sound.
Exercise
A function takes p: *mut i32 and runs let a = &mut *p; let b = &mut *p; *a += 1; *b += 1;. Even if p is valid and aligned, why is this UB, and how do you fix it?
Show answer
Both a and b are &mut references to the same i32 and are live at the same time. That violates the exclusivity rule, so the compiler may assume they do not overlap. Fix it by using the raw pointer directly: *p += 1; *p += 1;. Or create each reference only after the previous one is no longer used.