Skip to content
Tutorials Center
My learning

Topics

Lesson 72 of 132 ยท Smart Pointers and Memory

Unsafe Rust

Learn what unsafe Rust really allows, how raw pointers work, how to build safe abstractions like split_at_mut, why static mut is dangerous, and how Miri finds bugs.

Everything you have written so far is safe Rust: the compiler guarantees that your program has no use-after-free, no data races and no out-of-bounds reads (barring bugs in the compiler itself). That guarantee is Rust's biggest selling point, so it may surprise you that the language has an escape hatch, the keyword unsafe. Why would a memory-safe language include one?

Because some things cannot be checked by a compiler: talking to hardware, calling C libraries, and implementing the very building blocks that safe code relies on, such as Vec, Rc and Mutex. Those need operations the borrow checker cannot verify. unsafe is how you tell the compiler "I have checked this part myself". This lesson shows exactly what that means, how to use it in small, well-fenced doses, and how to avoid the dangerous parts. It builds on Memory Layout and Sizes and leads into FFI.

What unsafe does and does not do

unsafe does not turn off the borrow checker, and it does not turn off type checking. Inside an unsafe block, references are still checked as usual. What it unlocks is exactly five extra abilities:

  1. Dereference a raw pointer.
  2. Call an unsafe function or method (including foreign functions from C).
  3. Access or modify a mutable static variable.
  4. Implement an unsafe trait.
  5. Access the fields of a union.

Each of these has rules the compiler cannot verify. If you break them, you get undefined behavior (UB): the program is allowed to do anything, including appearing to work today and crashing after the next compiler upgrade. Undefined behavior is not "a crash"; it is a broken contract that lets the optimizer assume things that are false.

Unsafe code is not "dangerous code that is probably fine". A single unsound unsafe block can break the guarantees of the whole program, because safe code elsewhere trusts it. Use unsafe only when you can state, in a comment, why the rules hold.

The design principle to remember: unsafe code lives in small modules, behind safe APIs. The standard library is full of unsafe code, and you use it every day without writing the word.

Raw pointers

A raw pointer is *const T (read only) or *mut T (read/write). Unlike references, raw pointers:

  • may be null or dangling,
  • are not tracked by the borrow checker (you may have several *mut T to the same data),
  • do not clean anything up automatically,
  • may be freely cast to other pointer types and to integers.

Creating a raw pointer is safe. Only dereferencing it needs unsafe.

Rust Creating raw pointers is safe, reading through them is not

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

This program is valid, but only because both pointers came from a live local variable and nothing else touched value while they were in use. Strictly speaking, using read_only after writing through read_write would be questionable (the aliasing rules for raw pointers are subtle), which is why you should keep raw-pointer lifetimes short.

If you forget the unsafe block, the compiler tells you precisely what is missing:

Rust Dereferencing a raw pointer without unsafe (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

TEXT
error[E0133]: dereference of raw pointer is unsafe and requires unsafe block

Pointer arithmetic

Pointers can move through memory with add, sub and offset. Moving by n advances n * size_of::<T>() bytes. Reading past the end of the allocation is UB, even if you never read the value.

Rust Walking an array with a pointer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Notice the // SAFETY: comment. It is a strong convention (and a Clippy lint, undocumented_unsafe_blocks) to write one before every unsafe block, explaining why the conditions hold. Writing the comment often reveals a bug before the code runs.

Of course, items.iter().sum() does the same without any of this. Raw pointers earn their keep only when no safe API exists.

&raw const and &raw mut

Sometimes you need a pointer to a field that may be misaligned (for example in a repr(packed) struct) or to a value you must not create a reference to. Taking a normal reference first would already be UB. The operators &raw const place and &raw mut place (stable since Rust 1.82) create the raw pointer directly, with no intermediate reference.

Rust Raw borrow of a packed field

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Unsafe functions

A function marked unsafe fn has requirements the caller must uphold. The compiler cannot check them, so calling the function requires an unsafe block, and the function's documentation should list the requirements under a # Safety heading.

Rust Writing and calling an unsafe function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Look at the body of get_unchecked_by_hand: it has its own unsafe { ... } block even though the whole function is already unsafe fn. That is the 2024 edition behavior. The lint unsafe_op_in_unsafe_fn is now warn by default: an unsafe function no longer acts as one big unsafe block. The reason is clarity. "The caller must uphold a contract" (the signature) and "this specific operation is unsafe" (the block) are different things, and mixing them hid unsafe operations among safe code. In editions before 2024 the extra block was optional.

Prefer to expose a safe function whenever you can. If your unsafe function has a precondition that is cheap to check, check it and return Option or panic instead.

Building a safe abstraction: split_at_mut

The classic example: the borrow checker allows only one &mut borrow of a slice at a time. But two &mut borrows of non-overlapping halves are perfectly safe. The compiler cannot see that, so the standard library implements split_at_mut with a little unsafe code. Here is a version of the same idea:

Rust split_at_mut from scratch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

This is the model for all good unsafe code:

  • The function is safe to call. No caller can make it misbehave, because the assert! checks the one precondition.
  • The unsafe block is tiny and has a written justification.
  • The lifetimes in the signature still connect the output to the input, so the borrow checker keeps protecting the callers.

Without the unsafe code, the safe way to write it fails:

Rust Two mutable borrows of one slice (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

TEXT
error[E0499]: cannot borrow `numbers` as mutable more than once at a time

In real code, just call the standard library's split_at_mut. Write your own only when no existing safe API does what you need.

Static mutable variables

A static is a single global value with a fixed address for the whole program. A static mut can be changed, and every access is unsafe, because two threads (or two references) could touch it at the same time. Since the 2024 edition, creating a reference to a static mut is a hard error (static_mut_refs is deny-by-default), because such a reference is almost always unsound.

Rust A reference to a static mut (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The println! takes a reference to COUNTER, and the compiler rejects it:

TEXT
error: creating a shared reference to mutable static
  = note: `#[deny(static_mut_refs)]` (part of `#[deny(rust_2024_compatibility)]`) on by default

The fix for this lint, if you must keep the static, is to avoid the reference. You can sidestep the lint with &raw const or by copying the value into a local first, but the better answer is: do not use static mut. Use a safe alternative:

Rust Safe alternatives to static mut

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

AtomicU32 handles integers and flags; Mutex (with a const constructor, so it works in a static) handles anything bigger. For lazily built globals, OnceLock and LazyLock do the job; see Atomics and Memory Ordering. Plain static (immutable) and const values need no unsafe at all.

Unsafe traits

A trait is unsafe when implementing it carries a promise the compiler cannot check. The famous ones are Send and Sync (a type may be moved to, or shared with, another thread): if you claim a type is Sync but it is not, you cause data races. You write unsafe impl to make that promise.

Rust Declaring and implementing an unsafe trait

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Crates such as bytemuck offer a finished, audited version of this idea (Pod, Zeroable) for converting between plain-data types and bytes. Prefer a well-reviewed crate over rolling your own.

Unions

A union stores several fields in the same bytes, like a C union. Writing a field is safe, but reading one is unsafe, because the compiler cannot know which field was last written.

Rust Reading a float's bits through a union

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

You will rarely write a union in application code. They matter for C interop and for compact storage in low-level libraries. Rust's own enums are the safe, tagged equivalent. For reinterpreting bytes, to_bits, from_bits, to_le_bytes and from_le_bytes are safe and should be your first choice.

Undefined behavior: what you must never do

Even inside unsafe, these are always UB:

  • Dereferencing a null, dangling or misaligned pointer.
  • Reading uninitialized memory as if it were a valid value.
  • Creating a reference that is invalid: null, unaligned, dangling, or pointing to a value of the wrong type (for example a bool that is not 0 or 1).
  • Having a &mut T alias with any other live reference or pointer used to access the same memory.
  • Data races (unsynchronized access where at least one is a write).
  • Breaking an invariant of a type such as str (valid UTF-8) or NonZeroU32 (not zero).

A safe-looking example of a classic UB: String::from_utf8_unchecked with invalid bytes creates a str that violates its own invariant. Everything that later touches it, like chars(), may misbehave. The checked String::from_utf8 costs one validation pass and returns an error instead.

Finding bugs with Miri

Miri is an interpreter for Rust's mid-level IR that executes your program and reports undefined behavior: out-of-bounds access, use after free, invalid values, alignment errors and aliasing violations. It is slow but extremely effective at validating unsafe code and its tests. Miri is a rustup component, so you run it in a normal Cargo project, not in our in-browser editor:

Terminal
# Read-only: run on your own machine
rustup +nightly component add miri
cargo +nightly miri test
cargo +nightly miri run

If you maintain any unsafe code, run your test suite under Miri in continuous integration.

When to use unsafe, and when not

Use it when:

  • calling C or system APIs (FFI),
  • implementing a data structure that safe Rust cannot express (linked lists with back-pointers, arenas, intrusive structures; see Unsafe Data Structures),
  • a measured performance bottleneck needs it, and a safe alternative like iterators is truly not enough.

Avoid it when:

  • you only want to bypass a borrow checker error (restructure the code, use indices, Rc<RefCell<T>>, or split borrows instead),
  • you hope for speed without measuring (bounds checks are cheap and often optimized away),
  • a crate already offers an audited solution.

The checklist for every unsafe block: what are the preconditions, who guarantees them, and what would happen if they were false?

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which of these needs an unsafe block?

    Creating and passing raw pointers is safe. Dereferencing them is one of the five unsafe superpowers, because the compiler cannot prove the pointer is valid.
  2. 2. What does unsafe turn off?

    References are still borrow-checked inside unsafe blocks. The keyword grants five specific abilities and moves responsibility for them to you.
  3. 3. Why does the 2024 edition warn about unsafe operations directly in the body of an unsafe fn?

    The lint unsafe_op_in_unsafe_fn makes you wrap each unsafe operation in its own block, ideally with a SAFETY comment, instead of treating the whole function body as unsafe.
  4. 4. What is the best replacement for static mut COUNTER: u32 in a program with several threads?

    An atomic can be modified through a shared reference from any thread without data races, and needs no unsafe code.
  5. 5. What does Miri do?

    Miri executes the program step by step in an interpreter that tracks pointer validity, alignment and aliasing, so it can report many forms of undefined behavior.

Summary

  • unsafe unlocks five abilities: dereferencing raw pointers, calling unsafe functions, accessing static mut, implementing unsafe traits and reading union fields. The borrow checker stays on.
  • Creating raw pointers is safe, dereferencing is not; &raw const and &raw mut create pointers without an intermediate reference.
  • Undefined behavior is a broken contract, not a crash. Keep unsafe blocks small, document them with // SAFETY: and wrap them in safe APIs, as split_at_mut does.
  • In the 2024 edition, unsafe operations inside unsafe fn need their own block and references to static mut are denied. Prefer atomics, Mutex, OnceLock and LazyLock.
  • Test unsafe code with Miri, and prefer audited crates over hand-rolled layouts.

Next: FFI: Calling C and Being Called