Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Concepts

Unsafe Rust

Reference for unsafe Rust: the five unsafe operations, unsafe blocks, functions, traits and impls, undefined behavior, safe abstractions, safety comments and unsafe_op_in_unsafe_fn.

Safe Rust guarantees memory safety and freedom from data races. Some useful things cannot be proven safe by the compiler: talking to C, implementing Vec, reading hardware registers. The unsafe keyword marks code where you take responsibility for upholding the rules the compiler normally checks. It does not turn off the borrow checker or the type system; it unlocks exactly five extra operations.

The five superpowers: dereference a raw pointer, call an unsafe function (including foreign functions), access or modify a mutable static, implement an unsafe trait, and access fields of a union. Breaking the contract of any of them can cause undefined behavior (UB), which means the program has no defined meaning at all.

Rust
let x = 5;
let p = &x as *const i32;
let y = unsafe { *p }; // one of the five superpowers

Try it

Rust Raw pointers and unsafe blocks

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.

Rust A safe wrapper around unsafe code

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.

Rust unsafe fn, unsafe trait and 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.

The five operations

Operation Contract you must uphold
Dereference *const T / *mut T non-null, aligned, points to a live, initialized T, no aliasing violations
Call an unsafe fn whatever its # Safety docs require
Access a static mut no data race, no aliasing &mut
Implement an unsafe trait the trait's documented invariants (for example Send, Sync)
Read a union field the bytes form a valid value of the field's type

Edition 2024 also requires unsafe extern blocks, unsafe on attributes such as #[unsafe(no_mangle)], and warns on references to static mut (static_mut_refs), which is why the example takes addr_of_mut!.

What counts as undefined behavior

  • Dereferencing a dangling, null or misaligned pointer; reading uninitialized memory as a typed value.
  • Creating two live &mut to the same data, or a &mut alongside a & (aliasing).
  • Producing invalid values: a bool other than 0/1, a char outside the Unicode range, a dangling reference, an invalid enum discriminant.
  • A data race on non-atomic memory.
  • Breaking an invariant a safe type relies on (for example creating a str with invalid UTF-8).

Release and debug builds may both appear to work with UB; that is a trap, not a defense. Use Miri (cargo +nightly miri test) to detect many cases.

Usage notes

  • Keep unsafe blocks tiny and put a // SAFETY: comment above each, explaining why the contract holds. Document unsafe functions with a # Safety section.
  • Build safe abstractions: a public API that cannot cause UB from safe code is sound, even if it uses unsafe internally. If safe callers can trigger UB, the abstraction is unsound and is a bug.
  • Lint: unsafe_op_in_unsafe_fn (warn by default in edition 2024) forces explicit blocks inside unsafe functions; clippy's undocumented_unsafe_blocks can require SAFETY comments.
  • Prefer safe alternatives first: get, split_at_mut, chunks, MaybeUninit, Cell, Mutex. Reach for unsafe after measuring.
  • unsafe impl Send/Sync is a promise about thread safety; get it wrong and data races become possible.
  • FFI is the most common reason for unsafe: see FFI with C.