Sub topic 3
The five things unsafe allows
This chapter assumes you know ownership, borrowing, and lifetimes in safe Rust. It also assumes you know references, slices, structs, basic traits, and how to run a program with cargo run. The previous chapters covered why unsafe exists and what undefined behavior is. This chapter lists exactly what unsafe lets you do.
What an unsafe block changes
The unsafe keyword does not switch off the compiler. Type checking, name resolution, the borrow checker, and lifetime checking all keep running on code inside an unsafe block. A &mut reference inside an unsafe block is still checked as a &mut reference.
What unsafe does is unlock five operations. The compiler cannot prove these safe, so it makes you take responsibility for them. They are:
- Dereference a raw pointer.
- Call an unsafe function or method.
- Access or modify a mutable static variable.
- Implement an unsafe trait.
- Access a field of a union.
Nothing else needs unsafe. If you need something that is not on this list, such as skipping a bounds check, you reach it through one of these five. For example, you call an unsafe function like get_unchecked.
Why these five
Each operation hides a condition the compiler cannot check:
| Operation | Condition you must uphold |
|---|---|
| Dereference a raw pointer | The pointer is non-null, aligned, and points to a live, valid value |
| Call an unsafe function | The function's documented preconditions hold |
| Access a mutable static | No other thread touches it at the same time, and no aliasing rule breaks |
| Implement an unsafe trait | The type really satisfies the trait's promise |
| Read a union field | The bytes stored are a valid value of the field's type |
Unsafe code is code where you, not the compiler, have checked these conditions. If you get one wrong, the result is undefined behavior.
1. Dereferencing a raw pointer
Raw pointers are *const T and *mut T. You can create them in safe code, and you can pass them around, compare them, and print them. Only the dereference needs unsafe.
fn main() {
let mut num = 5;
let p = &mut num as *mut i32;
// Creating a pointer to an arbitrary address is also safe.
let wild = 0x1000 as *const i32;
println!("wild pointer is null: {}", wild.is_null());
// SAFETY: `p` points to `num`, which is alive, aligned, and initialized.
unsafe {
*p += 1;
println!("num through pointer: {}", *p);
}
}Dereferencing wild would be undefined behavior, because nothing guarantees that address holds an i32. Raw pointers are not checked for null, alignment, or validity. They also ignore the borrowing rules. You can hold a *mut i32 and a *const i32 to the same value, and the compiler accepts both. The next chapter covers raw pointers in detail.
2. Calling an unsafe function
A function marked unsafe fn has preconditions the compiler cannot check. The caller must read them and make sure they hold. Standard library examples are slice::get_unchecked, String::from_utf8_unchecked, and Vec::set_len.
fn main() {
let values = vec![10, 20, 30];
let i = 1;
assert!(i < values.len());
// SAFETY: `i` was checked against the length on the line above,
// so the index is in bounds.
let x = unsafe { *values.get_unchecked(i) };
println!("{x}");
}Calling get_unchecked(5) here would compile and might appear to work, but it reads past the end of the allocation. That is undefined behavior.
Foreign functions are in this category too. A function declared in an extern block is unsafe to call, because the compiler cannot see C code. In the 2024 edition the block itself is written unsafe extern.
unsafe extern "C" {
fn abs(input: i32) -> i32;
}
fn main() {
// SAFETY: C's `abs` has no preconditions beyond a valid i32 argument.
let v = unsafe { abs(-3) };
println!("{v}");
}Unsafe function bodies
In the 2024 edition, the body of an unsafe fn is not an unsafe context by default. The lint unsafe_op_in_unsafe_fn warns when you do something unsafe in it without an inner unsafe block. This is why the examples in this tutorial wrap the body of an unsafe function in its own block. The signature says "callers must uphold a contract". The inner block says "this exact operation is where I rely on it". Keeping those two jobs separate makes review easier.
3. Accessing a mutable static
A static item lives for the whole program. An immutable static is safe to read. A static mut is a global that any code can change, so reading or writing it is unsafe. Two threads could write at once, which is a data race.
static mut COUNTER: u32 = 0;
fn add_to_count(inc: u32) {
// SAFETY: this program is single-threaded, so there are no data races.
unsafe {
COUNTER += inc;
}
}
fn main() {
add_to_count(3);
// Copy the value out instead of taking a reference to the static.
let value = unsafe { COUNTER };
println!("{value}");
}Note the comment about copying the value out. In the 2024 edition, creating a & or &mut reference to a static mut is denied by the static_mut_refs lint. A reference to a global can easily end up aliased with another reference, and that is undefined behavior even in a single thread. Use plain reads and writes, or take a raw pointer with &raw const COUNTER or &raw mut COUNTER.
In most programs you do not need static mut at all. AtomicU32, Mutex, and OnceLock give you shared mutable state with no unsafe in your code. A later chapter covers mutable statics in more depth.
4. Implementing an unsafe trait
A trait is unsafe when implementing it makes a promise the compiler cannot check, and other code relies on that promise. The best known examples are Send and Sync. If you wrongly implement Send for a type, safe code in other crates can move it across threads and cause a data race.
Implementing an unsafe trait needs unsafe impl. Using the trait does not.
/// # Safety
///
/// Implementors must be valid when every byte is zero.
unsafe trait ZeroValid {
fn zeroed() -> Self
where
Self: Sized,
{
// SAFETY: the trait's contract says all-zero bytes are valid for `Self`.
unsafe { std::mem::zeroed() }
}
}
// SAFETY: zero is a valid u32.
unsafe impl ZeroValid for u32 {}
// SAFETY: zero is a valid f64 (0.0).
unsafe impl ZeroValid for f64 {}
fn main() {
let a = u32::zeroed();
let b = f64::zeroed();
println!("{a} {b}");
}Writing unsafe impl ZeroValid for &u8 {} would compile, but all-zero bytes are a null reference, which is invalid. The unsafe keyword on the impl is where you take blame for that mistake. Note that the trait's default method contains its own unsafe block. The trait contract is what justifies it.
5. Accessing a union field
A union stores several fields in the same memory. Rust cannot know which field was last written, so it cannot know that a read yields a valid value. Writing a Copy field is safe. Reading any field is unsafe.
union IntOrFloat {
i: u32,
f: f32,
}
fn main() {
let u = IntOrFloat { f: 1.0 };
// SAFETY: every 32-bit pattern is a valid u32, so reading the
// bytes of an f32 as a u32 is fine.
let bits = unsafe { u.i };
println!("{bits:#x}");
}This prints 0x3f800000, the bit pattern of 1.0f32. The read is sound because every 32-bit pattern is a valid u32. Reading a bool field out of a union that holds the byte 2 would be undefined behavior, because bool only allows 0 and 1. Unions are used mostly for C interop. For plain bit reinterpretation, f32::to_bits does the same job in safe code.
Unsafe blocks versus unsafe declarations
The keyword appears in two roles, and it helps to keep them apart.
- An
unsafe { ... }block says "I have checked the conditions for the operations inside". unsafe fn,unsafe trait, andunsafe externsay "someone else must check conditions here".unsafe implsays "I have checked the conditions this trait requires".
Because of the second role, a safe function can contain an unsafe block and still be safe to call. That is how the standard library gives you Vec::push on top of raw pointers. It is the subject of a later chapter on safe abstractions.
Common mistakes
- Treating
unsafeas "turn off the borrow checker". References inside the block are still checked. - Forgetting that creating a raw pointer is safe, so a bad pointer can exist long before the unsafe dereference.
- Taking
&mut COUNTERon astatic mutinstead of copying the value or using a raw pointer. - Writing
unsafe impl Sendto silence a compiler error without checking that the type can actually move between threads. - Reading a union field whose bytes are not a valid value of that type.
Exercise
A colleague writes let p = &x as *const i32; let q = p.wrapping_add(1_000_000); outside any unsafe block, and it compiles. Why does this compile, and which operation would need unsafe?
Show answer
Creating and offsetting a raw pointer with wrapping_add is safe, because it never touches memory. The compiler accepts q even though it points far outside x. Only dereferencing q, for example *q, is one of the five unsafe operations. That dereference would be undefined behavior here.
Exercise
Name which of the five unsafe operations each line uses: (a) unsafe { v.get_unchecked(0) }, (b) unsafe impl Send for Handle {}, (c) unsafe { COUNTER += 1 } where COUNTER is a static mut, (d) unsafe { u.f } where u is a union.
Show answer
(a) calling an unsafe function, (b) implementing an unsafe trait, (c) accessing a mutable static, (d) accessing a union field.