Sub topic 5
Unsafe functions and writing safety contracts
This chapter assumes you know ownership, borrowing, and lifetimes in safe Rust. It also assumes you know basic traits and how to run a program with Cargo. You should already have met raw pointers and the unsafe block.
What an unsafe function is
An unsafe fn is a function whose caller must uphold conditions the compiler cannot check. The function body is still ordinary Rust. The keyword changes who is responsible. For a safe function, the compiler guarantees that no caller can cause undefined behavior through it. For an unsafe function, the caller carries that duty.
That split gives you two roles:
- The author of an unsafe function states what must be true before the call.
- The caller checks that those conditions hold and writes
unsafeto say so.
The stated conditions are the safety contract. If the caller meets the contract, the function behaves correctly. If the caller breaks it, the behavior is undefined.
Writing the contract
Put the contract in a # Safety section of the doc comment. List each requirement as a concrete, checkable condition. "The pointer must be valid" is vague. "The pointer must be non-null, aligned for u32, and point to an initialized u32" can be checked.
/// 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}");
}Two details in this code are worth noting.
First, the body of read_u32 has its own unsafe block. Since Rust 2024, the unsafe_op_in_unsafe_fn lint warns when an unsafe operation appears in an unsafe function without one. The block marks exactly which operation depends on the contract.
Second, the call site has a // SAFETY: comment. It explains why each requirement of the contract holds here. A reader can then compare the comment against the # Safety section, line by line.
The two halves of the pattern
| Where | What you write | What it answers |
|---|---|---|
| Definition | `# Safety` doc section | What must the caller guarantee? |
| Call site | `// SAFETY:` comment | Why does it hold here? |
Choosing between safe and unsafe
Mark a function unsafe when some inputs can cause undefined behavior and the function cannot detect them. Keep it safe when it can check the condition itself, for example with assert!. A function that is safe to call but can cause undefined behavior from safe code is unsound. That is a bug in the function, not in the caller.
Ask one question: can any caller, using only safe code, trigger undefined behavior through this function? If yes, either add a check or mark it unsafe.
Common errors
- Vague contracts. Wording like "must be valid" gives callers nothing to verify. Name the properties: non-null, aligned, initialized, in bounds, not aliased.
- Missing
# Safetysection. Clippy'smissing_safety_doclint flags public unsafe functions without one. - Copying a
SAFETYcomment. A comment that says "this is fine" proves nothing. Say which fact makes each condition true. - Wide unsafe blocks. Put only the operations that need
unsafeinside the block. A narrow block shows which line relies on the contract. - Hidden requirements. If the function also needs the pointer to outlive a lifetime, or needs exclusive access, write that down too.
Exercise
A function unsafe fn first(ptr: *const i32) -> i32 { unsafe { *ptr } } has no documentation. Write the # Safety section it needs, then say why a caller passing std::ptr::null() breaks the contract.
Show answer
The section should read: "ptr must be non-null, aligned for i32, and point to an initialized i32 that is valid for reads." A null pointer breaks the non-null requirement. Dereferencing it is undefined behavior, so the caller, not the function, is at fault.