Sub topic 3
The Five Things Unsafe Allows
This chapter assumes you know ownership, borrowing, and lifetimes in safe Rust. It also assumes you can read basic trait and generic code and can run a program with Cargo.
What an unsafe block changes
An unsafe block does not turn off the borrow checker or type checking. Inside it, references are still checked, moves still move, and types still have to match. The block unlocks exactly five operations that the compiler cannot verify. For these, you take responsibility for correctness.
1. Dereference a raw pointer
Creating a raw pointer (*const T or *mut T) is safe. Following it is not, because the compiler cannot know whether it is null, dangling, or misaligned.
fn main() {
let mut num = 5;
let p = &mut num as *mut i32;
unsafe {
*p += 1;
println!("num through pointer: {}", *p);
}
}2. Call an unsafe function or method
An unsafe fn has requirements that the type system cannot express. The caller must meet them. Foreign functions declared in an extern block fall into this category too.
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}");
}The SAFETY: comment states why the call is valid. Write one for every unsafe block.
3. Access or modify a mutable static
A static mut is global state that any thread can reach, so the compiler cannot rule out data races.
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}");
}Copying the value out avoids creating a reference to the static. Such references are easy to make invalid, and recent compilers warn about them.
4. Implement an unsafe trait
A trait is unsafe when implementors must uphold a promise the compiler cannot check. Send and Sync are the common examples. Raw pointers are not Send, so a wrapper has to opt in.
struct SendPtr(*mut u8);
// SAFETY: the pointer is only used by one thread at a time and points to
// memory that is valid on any thread.
unsafe impl Send for SendPtr {}
fn main() {
let mut byte = 1u8;
let p = SendPtr(&mut byte as *mut u8);
let handle = std::thread::spawn(move || {
let p = p;
// SAFETY: `byte` outlives the thread because we join below.
unsafe { *p.0 = 2 };
});
handle.join().unwrap();
println!("{byte}");
}Here unsafe impl means "I vouch for this." The compiler then trusts you when it checks thread::spawn.
5. Read a union field
A union stores several fields in the same memory. Rust cannot know which field was written last, so reading one is unsafe. Writing a Copy field is safe.
union IntOrFloat {
i: u32,
f: f32,
}
fn main() {
let u = IntOrFloat { f: 1.0 };
// SAFETY: every bit pattern is a valid u32, and `f` was fully written.
let bits = unsafe { u.i };
println!("{bits:#x}");
}This prints 0x3f800000, the bit pattern of 1.0f32.
Common errors
- Putting a large function body in one
unsafeblock. Wrap only the operations that need it, so reviewers can see what you are vouching for. - Treating
unsafeas permission to ignore the borrow rules. Creating two live&mutreferences to the same data is still undefined behavior, even in an unsafe block. - Omitting the
SAFETY:comment. Without it, nobody can tell whether the code is correct or just compiles.
Exercise
Which of these needs an unsafe block: (a) creating a *const i32 from a reference, (b) reading *p through that pointer, (c) calling println!?
Show answer
Only (b). Creating a raw pointer is safe, and println! is an ordinary safe macro. Dereferencing the raw pointer is one of the five unsafe operations, because the compiler cannot verify that the pointer is valid.
Exercise
Name the five operations that unsafe unlocks.
Show answer
Dereferencing a raw pointer, calling an unsafe function or method, accessing or modifying a mutable static, implementing an unsafe trait, and reading a union field.