Sub topic 1
Why Rust has an unsafe escape hatch
Prerequisites
This chapter assumes you already know the following:
- Ownership, borrowing, and lifetimes in safe Rust, including the rule that you can have many shared references or one mutable reference to a value.
- References, slices, and structs.
- Basic traits and generics.
- How to build and run a program with Cargo.
You do not need to know anything about unsafe Rust yet. This chapter explains why it exists. Later chapters cover its details.
The problem the compiler cannot solve
Safe Rust gives you a strong promise. If your program compiles without unsafe, it cannot cause memory errors such as use-after-free, double free, buffer overflow, or data races. The compiler enforces this with the ownership and borrowing rules.
Those rules are conservative. The compiler must decide, from the source text alone, whether a program is safe. Some questions cannot be answered that way:
- Is this pointer valid right now?
- Do these two ranges of one array overlap?
- Is the code on the other side of a C function call well behaved?
- Does this hardware register live at this address?
A static analysis that accepts every correct program and rejects every incorrect one is impossible in general. Rust chooses to reject some correct programs rather than accept an incorrect one. That keeps safe code trustworthy, but it also blocks useful code.
Unsafe Rust exists to close that gap. It lets you tell the compiler: "I know something you cannot check, and I take responsibility for it."
A program the borrow checker rejects
Consider a function that splits one mutable slice into two mutable slices at an index. The two halves never overlap, so the result is fine. The borrow checker cannot see that, because it only knows that both borrows come from the same slice.
fn split_at_mut(values: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
let len = values.len();
assert!(mid <= len);
(&mut values[..mid], &mut values[mid..])
}This fails to compile with an error that values cannot be borrowed as mutable more than once at a time. The code is correct, but proving it requires reasoning about index ranges, and the borrow checker does not do that.
The standard library already provides split_at_mut. Its implementation uses unsafe code internally, and its public signature is safe. This pattern, unsafe inside and safe outside, is the central idea of this tutorial.
What unsafe does and does not do
The unsafe keyword does not turn off the borrow checker, type checking, or any other compiler check. It adds a small set of extra abilities. Everything else still applies inside an unsafe block.
For example, this code still fails to compile, even though it sits in an unsafe block:
fn main() {
let s = String::from("hello");
let t = s;
unsafe {
println!("{}", s);
}
println!("{}", t);
}The compiler reports a use of the moved value s. Ownership rules are enforced everywhere.
What unsafe does is permit a short list of operations whose correctness the compiler cannot verify. The next chapters cover the list in detail. In summary, you may:
- Dereference a raw pointer.
- Call an unsafe function or method.
- Access or modify a mutable static variable.
- Implement an unsafe trait.
- Access fields of a union.
Each of these is a place where the compiler would need a fact it cannot get. The unsafe keyword marks the spot where you supply that fact.
Two meanings of the keyword
The word unsafe appears in two roles, and it helps to keep them apart.
| Role | Where it appears | What it means |
|---|---|---|
| Obligation for the caller | `unsafe fn`, `unsafe trait` | Whoever uses this must meet conditions that the compiler cannot check. |
| Discharge of an obligation | `unsafe { ... }`, `unsafe impl` | The author asserts that the conditions hold at this point. |
An unsafe fn says: "There are rules for calling me, and breaking them is undefined behavior." An unsafe block says: "I have checked those rules here." The two fit together as a contract between the author of an API and the person using it.
The first example
Here is the smallest useful case. Creating a raw pointer is safe. Dereferencing it needs unsafe.
fn main() {
let mut num = 5;
let p = &mut num as *mut i32;
unsafe {
*p += 1;
println!("num through pointer: {}", *p);
}
}This prints num through pointer: 6.
The cast &mut num as *mut i32 is allowed anywhere, because a pointer that is never read or written cannot cause harm. The dereference *p is where harm could happen. If p were dangling, null, or misaligned, the read would be undefined behavior. The compiler cannot tell whether p is valid, so it requires you to write unsafe and take responsibility.
Here the pointer comes from a live &mut i32, so it is valid. The unsafe block is correct, and the program is sound.
Why not make everything safe, or everything unsafe
Two other designs are possible, and both have costs.
- No escape hatch. The language would have to forbid anything it cannot prove. You could not write
Vec,Rc,Mutex, or an operating system driver in Rust. Every such feature would have to be built into the compiler. Interacting with C libraries and hardware would be impossible. - Everything unsafe by default. This is the situation in C and C++. Any line can cause undefined behavior, so a bug can hide anywhere in the codebase.
Rust takes a middle path. Most code is safe and checked. A small, clearly marked subset is unchecked. When a memory bug appears in a Rust program, you know where to look first: in the unsafe blocks, or in the safe code those blocks depend on.
Unsafe code is also how the standard library builds its safe types. Vec<T> manages raw memory with unsafe code. Users of Vec<T> never write unsafe, because the type's safe API prevents misuse.
Soundness: the property you are aiming for
A safe API is sound if no sequence of safe calls to it can cause undefined behavior. An API is unsound if safe code can trigger undefined behavior through it.
Soundness is the standard you will hold your own unsafe code to. This has an important consequence for how you think about responsibility:
- If a bug requires a caller to write
unsafe, the caller is at fault when they break the documented rules. - If a bug can be triggered from entirely safe code, the author of the unsafe code is at fault, even if the unsafe block itself looks small and the bug is elsewhere.
That second point surprises many people. Unsafe code relies on facts about the surrounding safe code. If a safe function maintains a wrong length field, an unsafe block that trusts that field is the broken part of the design. The scope of "the code that must be reviewed" therefore reaches beyond the unsafe block itself, to everything that can affect the facts the block depends on. This is why later chapters stress keeping those facts private to a module.
A map of the rest of the tutorial
The tutorial follows the dependencies between ideas.
You are at the top. The next chapter defines undefined behavior, because every rule in the rest of the tutorial exists to avoid it.
Common misunderstandings
- "Unsafe means the code is dangerous or wrong." It means the compiler is not checking some facts and you are. Correct unsafe code is normal in the standard library.
- "Unsafe turns off the borrow checker." It does not. References inside an
unsafeblock are still checked. Only the listed operations are unlocked. - "A function with an unsafe block must itself be unsafe." No. If the function upholds all requirements internally for every possible input, it should be a safe function. That is what makes safe abstractions possible.
- "If it works in testing, it is fine." Undefined behavior can appear to work for years and then break after a compiler upgrade or a different optimization level. Tests do not prove soundness.
Summary
- Safe Rust rules out memory errors, but the compiler is conservative and cannot verify everything.
unsafeunlocks five specific operations and leaves all other checks on.- An unsafe function states a contract. An unsafe block claims the contract holds.
- Good unsafe code hides behind a sound safe API, so callers never need to write
unsafe. - Soundness is the goal: safe code must never be able to cause undefined behavior through your API.
Exercise
The following function compiles only if you add unsafe somewhere. Which operation needs it, and why can the compiler not check it for you?
fn read_first(p: const i32) -> i32 {
p
}
Show answer
The dereference *p of a raw pointer needs an unsafe block. The compiler cannot know whether p is null, dangling, or misaligned, so it cannot prove the read is valid. Wrapping the dereference in unsafe { *p } compiles, but then the function is only sound if every safe caller is prevented from passing an invalid pointer. In practice you would mark the function unsafe fn and document the requirement in a # Safety section.
Exercise
A colleague says that putting code inside an unsafe block lets them use a value after it has been moved. Is that correct? Explain what unsafe does allow.
Show answer
It is not correct. unsafe does not disable the borrow checker or move checking, so using a moved value is still a compile error. unsafe only permits five operations: dereferencing raw pointers, calling unsafe functions, accessing mutable statics, implementing unsafe traits, and reading union fields.
Exercise
A safe public function in your library contains an unsafe block that reads from a pointer. A user calls the function from safe code with a certain argument and gets a crash. Who is responsible for the bug, and what does that tell you about soundness?
Show answer
The library author is responsible. A safe function must be sound, meaning no safe call can cause undefined behavior. If safe code can trigger the crash, the function is unsound. The fix is to check the argument inside the function, or to mark the function unsafe fn and document the requirement so that callers take on the obligation.