Sub topic 5
Unsafe functions and writing safety contracts
This chapter assumes you know ownership, borrowing, and lifetimes in safe Rust, and that you have seen raw pointers and unsafe blocks. It covers how to declare a function as unsafe, how to write down what callers must guarantee, and how to justify each call. Safe abstractions come in a later chapter.
What `unsafe fn` means
An unsafe fn is a function that has requirements the compiler cannot check. If a caller breaks those requirements, the program can have undefined behavior (UB). Calling such a function requires an unsafe block, which is how the caller says "I have checked the requirements."
The keyword moves a responsibility. Safe code can promise nothing about arguments the compiler cannot verify, so the function's author lists the requirements and the caller must meet them.
The rule for choosing between safe and unsafe is simple. If any possible call from safe code, with any argument values, could cause UB, the function must be unsafe. A function that is safe to call and can cause UB through safe-only use is called unsound. Unsoundness is a bug in the function, not in the caller.
A first example
This is the function from the chapter plan. It reads a u32 through a raw pointer.
/// Reads a `u32` through a raw pointer.
///
/// # Safety
///
/// `ptr` must be non-null, aligned for `u32`, and point to an initialized `u32`
/// that is valid for reads.
unsafe fn read_u32(ptr: *const u32) -> u32 {
unsafe { ptr.read() }
}
fn main() {
let x: u32 = 7;
// SAFETY: `&x` is a valid, aligned pointer to an initialized u32.
let y = unsafe { read_u32(&x) };
println!("{y}");
}The code has two separate pieces of unsafe bookkeeping.
- The
# Safetysection in the doc comment is the contract. It is written for callers. - The
// SAFETY:comment at the call site is the justification. It is written for reviewers, and it explains why the contract holds at that exact spot.
Unsafe operations inside an unsafe function
Older Rust treated the whole body of an unsafe fn as an unsafe block. That made it easy to perform risky operations without noticing. In edition 2024 the unsafe_op_in_unsafe_fn lint warns by default, so each unsafe operation in the body needs its own unsafe block. That is why read_u32 wraps ptr.read() in unsafe { ... }.
This split gives you two distinct facts:
- The
unsafeon the function says "callers must uphold a contract." - The
unsafeblock inside says "I, the author, have checked that this operation is fine given the contract."
You can enable the same lint on older editions with #![warn(unsafe_op_in_unsafe_fn)] at the crate root.
What belongs in a safety contract
A good contract lists every condition that must hold before the call. It must be complete, because anything left out is a trap for the caller. It must also be checkable, because a caller must be able to decide whether it holds.
Most contracts draw from a few categories:
| Category | Example requirement |
|---|---|
| Pointer validity | `ptr` is non-null and points to `len` valid elements |
| Alignment | `ptr` is aligned for `T` |
| Initialization | The pointed-to memory holds a properly initialized `T` |
| Aliasing | No other reference or pointer accesses this memory while the returned `&mut` is alive |
| Lifetime | The memory stays allocated for as long as the returned reference is used |
| Bounds | `index < values.len()` |
| Threading | No other thread accesses the memory during the call |
Write requirements as facts about the arguments and the program state, not as advice. "Be careful with the pointer" is not a contract. "ptr must be valid for reads of size_of::<u32>() bytes" is one.
Rust's standard library documents its unsafe functions the same way. For example, std::slice::from_raw_parts lists pointer validity, alignment, initialization, lifetime, and a size limit. Reading a few of those pages shows the level of detail to aim for.
Writing a second unsafe function
A contract can be as simple as a bounds condition. Here is an unchecked read next to a safe wrapper that upholds the contract itself.
/// Returns the element at `index` without a bounds check.
///
/// # Safety
///
/// `index` must be less than `values.len()`.
unsafe fn get_unchecked(values: &[i32], index: usize) -> i32 {
debug_assert!(index < values.len());
// SAFETY: the caller guarantees `index < values.len()`, so the offset
// stays inside the slice's allocation.
unsafe { *values.as_ptr().add(index) }
}
fn get(values: &[i32], index: usize) -> Option<i32> {
if index < values.len() {
// SAFETY: we just checked `index < values.len()`.
Some(unsafe { get_unchecked(values, index) })
} else {
None
}
}
fn main() {
let data = [10, 20, 30];
println!("{:?}", get(&data, 1));
println!("{:?}", get(&data, 9));
}Three details are worth noting.
debug_assert!checks the contract in debug builds and costs nothing in release builds. It turns a silent UB into a loud panic while you test. It does not replace the contract, because release builds skip it.getis a safe function. It can be safe because it performs the check itself, so no argument value can cause UB.- A call such as
get_unchecked(&data, 9)would break the contract. The compiler would accept it, and the result would be undefined behavior. A debug build would panic, but a release build might read arbitrary memory or appear to work.
Writing the SAFETY comment at the call site
The // SAFETY: comment answers one question: why does each requirement hold here? A weak comment restates the contract. A strong comment points to the evidence.
Weak:
// SAFETY: the pointer is valid.Strong:
// SAFETY: `p` comes from `Vec::as_ptr` on `buf`, which is still alive and
// has `len >= 4`, and `u32` has no alignment problem because `buf` is a Vec<u32>.A useful habit is to go through the contract line by line and address each item, even if briefly. If you cannot justify one requirement, you have found a bug or a missing check.
Clippy can enforce both halves of the convention:
clippy::missing_safety_docwarns when a publicunsafe fnhas no# Safetysection.clippy::undocumented_unsafe_blockswarns when anunsafeblock has no// SAFETY:comment. It is off by default, so enable it in your crate.
#![warn(clippy::undocumented_unsafe_blocks)]
#![warn(unsafe_op_in_unsafe_fn)]
fn main() {
let x = 5u8;
let p = &x as *const u8;
// SAFETY: `p` was just created from a live reference to `x`.
let y = unsafe { *p };
println!("{y}");
}Common errors
- Marking a function safe because you "know" how it is used. The compiler and every other crate see only the signature. If a safe caller can break it, it must be
unsafe, or it must check the condition itself. - Writing an incomplete contract. A function that needs a pointer to be aligned but never says so is as dangerous as one with no documentation.
- Relying on
debug_assert!as the only protection. It disappears in release builds. Useassert!if the check is cheap and a panic is better than UB. - Using
unsafe fnas a shortcut for "this is dangerous or hard." The keyword means a compiler-unverifiable contract. A function that might return a wrong answer or panic is not unsafe in this sense. - Treating the
unsafeblock as covering the whole function. Keep each block as small as the one operation it justifies, so reviewers can see exactly what is being claimed.
Unsafe function pointers and traits
Functions can also be unsafe in other positions. A function pointer type can be unsafe fn(i32) -> i32. A safe fn item coerces to it, but not the other way around. A trait can declare methods as unsafe fn, and then implementors must provide an unsafe method with the same contract. Each of these follows the same rule: the contract lives in the documentation, and the caller proves it.
Exercises
Exercise
A function unsafe fn first(ptr: *const i32) -> i32 { unsafe { *ptr } } has no documentation. Write the # Safety section it needs.
Show answer
It must state that ptr is non-null, aligned for i32, and points to an initialized i32 that is valid for reads. For example: "ptr must be non-null, properly aligned for i32, and point to an initialized i32 that is valid for reads for the duration of the call."
Exercise
A safe function fn at(v: &[u8], i: usize) -> u8 { unsafe { *v.as_ptr().add(i) } } compiles. Is it sound, and how do you fix it?
Show answer
It is unsound. Safe code can pass any i, including one at or beyond v.len(), which reads out of bounds and is UB. Fix it by either making it unsafe fn with the contract "i < v.len()", or keeping it safe and checking, for example assert!(i < v.len()) before the unsafe read, or returning Option<u8>.
Exercise
Why does edition 2024 warn when you perform an unsafe operation in an unsafe fn without an inner unsafe block?
Show answer
The unsafe on the function only means callers must meet a contract. It does not mean the author checked each operation in the body. The lint forces each unsafe operation into its own block, so the author must justify it and reviewers can see exactly which operations carry risk.