Sub topic 1
Unsafe Rust: Powers, Contracts, and Safe Abstractions
Prerequisites
This chapter assumes you understand ownership, borrowing, lifetimes, references, slices, structs, traits, generics, and basic Cargo commands.
Why Rust Has an Unsafe Escape Hatch
Rust prevents many memory errors at compile time. However, some valid programs cannot be expressed using only safe Rust. Examples include operating-system interfaces, foreign-function interfaces (FFI), custom allocators, and low-level data structures.
An unsafe block tells Rust that you will uphold rules the compiler cannot verify. It does not disable type checking, ownership checking, or borrow checking. It only permits specific operations that need a human-reviewed safety argument.
fn main() {
let mut number = 5;
let pointer = &mut number as *mut i32;
// SAFETY: `pointer` came from a valid, exclusive reference, and `number`
// is still alive and has not been accessed through another reference.
unsafe {
*pointer += 1;
}
println!("{number}");
}What Undefined Behavior Means
Undefined behavior (UB) occurs when a program violates assumptions required by Rust's execution model. The compiler may then produce any result: incorrect output, a crash, or behavior that changes after an optimization.
Common causes include dereferencing a null, dangling, or misaligned pointer; creating overlapping mutable references; reading uninitialized bytes as a value; and using an invalid value for a type. UB is different from a normal Result error or panic because the language no longer guarantees what happens.
The Five Things Unsafe Allows
Rust restricts five categories of operations:
- Dereferencing a raw pointer.
- Calling an
unsafe fnor method. - Accessing a mutable
static. - Accessing a field of a union.
- Implementing an
unsafe trait.
Calling a foreign function through an extern declaration is also unsafe because Rust cannot verify the foreign code or its contract.
flowchart TD
A[Unsafe operation] --> B[Compiler cannot prove safety]
B --> C[Programmer states the invariant]
C --> D[Small reviewed unsafe block]
D --> E[Safe behavior for callers]Working with Raw Pointers
A raw pointer, written *const T or *mut T, stores an address without Rust's usual reference guarantees. Creating one is safe. Dereferencing one is unsafe. Before dereferencing, ensure that it is non-null, properly aligned, points to initialized data, and remains valid for the access.
Keep unsafe code small. Prefer converting it into a safe abstraction that checks its preconditions once, rather than requiring every caller to repeat the same reasoning.
Exercise
Why does creating a raw pointer not require unsafe, while reading through it does?
Show answer
Creating the address does not access memory. Dereferencing reads or writes memory, so the programmer must prove that the pointer is valid, aligned, initialized, and appropriately accessed.