skip to content

Raw Pointers and Superpowers

unsafe grants a few extra powers, such as dereferencing raw pointers and calling unsafe functions, and turns off no other checks. Interviewers ask what unsafe does not disable.

on this pageshow

questions

5

In Rust, what can code inside an `unsafe` block do that safe code cannot, and which compiler checks keep running inside it?

level: juniorimportance: must knowfreq 78%

answer

  1. a short fixed list
  2. raw pointers, unsafe calls, statics
  3. unions and unsafe traits too
  4. borrow checker never sleeps

basics

~20 s

An unsafe block unlocks a few operations: dereferencing raw pointers, calling unsafe functions, using a static mut and reading union fields, while unsafe impl covers unsafe traits. Borrow checking, type checking and bounds checks all stay on.

solid answer

~40 s

The Book counts five superpowers: dereference a raw pointer, call an unsafe function or method, access or modify a `static mut`, implement an unsafe trait (with `unsafe impl`), and read union fields. The Reference adds rarer cases, such as calling a `#[target_feature]` function from code lacking that feature, or applying an unsafe attribute. Nothing else changes. References inside the block are still borrow-checked, so two `&mut v` still fail with E0499; types are still checked; `v[10]` still panics on its bounds check. If a block contains none of the unlocked operations, rustc warns ``unnecessary `unsafe` block``. What `unsafe` really does is move responsibility: the compiler stops checking those few operations and the author promises their preconditions hold, which is why reviewers want each block small and explained.

code

rust · 9 lines
rust
fn main() {
    let mut v = vec![1, 2, 3];
    unsafe {
        let a = &mut v;
        let b = &mut v; // still borrow-checked inside unsafe
        a.push(4);
        b.push(5);
    }
}

go deeper

for a junior

Recite the five operations the Book lists and say plainly that borrow checking and type checking still run inside an unsafe block.

for a middle

Explain unsafe as moving a few proofs from the compiler to the author, and back it with an E0499 that still fires inside the block.

for a senior

Know the Reference's longer list, including target_feature calls and unsafe attributes, and argue for one small, commented block per operation in review.

for a principal

Treat the short list as an audit boundary: because undefined behaviour can only arise through these operations, a team can search for, count and review exactly that code.

## What the keyword unlocks `unsafe` in Rust is not a mode that switches the compiler off. It unlocks a short, fixed list of operations that the compiler cannot prove harmless, and it moves the proof of those operations onto the programmer. The Rust Book calls them the five **unsafe superpowers**: 1. **Dereference a raw pointer** (`*const T` or `*mut T`), with `*p` or with a method such as `p.read()`. 2. **Call an unsafe function or method**, such as `slice::get_unchecked`, `ptr::read` or a foreign function. 3. **Access or modify a mutable static**, a `static mut` item. 4. **Implement an unsafe trait**, which is written `unsafe impl` rather than inside a block. 5. **Access fields of a union**: reading one is unsafe; the Reference exempts plain assignment to a field. The Reference's chapter on unsafety gives the complete list, and it is slightly longer than the Book's five. It adds calling a function marked `#[target_feature]` from code that does not enable the same features, declaring an `extern` block (which the 2024 edition writes as `unsafe extern`), and applying an unsafe attribute such as `#[unsafe(no_mangle)]`. Those last two belong to the material on foreign function calls; the five above are what everyday unsafe code uses. ## What it does not switch off Everything else the compiler checks still runs inside an `unsafe` block: - **The borrow checker.** References keep their rules: two live `&mut v` fail with E0499, exactly as in safe code. - **Type checking.** A mismatched type is still E0308; `unsafe` never lets you treat one type as another without an explicit conversion such as a pointer cast or `mem::transmute`. - **Lifetimes.** A reference that would outlive its referent is still rejected. - **Runtime checks in std.** `v[10]` on a three-element `Vec` still panics with "index out of bounds"; skipping the check means calling a different, unsafe method. - **Privacy and visibility.** A private field stays private; `unsafe` grants no access across module boundaries. The Book's wording is direct: `unsafe` "doesn't turn off the borrow checker or disable any of Rust's other safety checks." What you gain is the right to use raw pointers, which are not borrow-checked at all, and to call functions whose preconditions the compiler cannot see. ## Proof from the compiler The snippet in this question's code example puts two mutable borrows of one `Vec` inside an `unsafe` block. rustc 1.99.1 rejects it with ``error[E0499]: cannot borrow `v` as mutable more than once at a time``, and it also warns ``unnecessary `unsafe` block`` (the `unused_unsafe` lint), because nothing inside the block is one of the unlocked operations. That second message is a useful habit-breaker: an `unsafe` block around ordinary code does nothing at all. ## Where the keyword appears The same keyword shows up in several positions, and each one says who carries a proof obligation: | Position | Meaning | Who must uphold the condition | |---|---|---| | `unsafe fn` | calling it has preconditions the compiler cannot check | every caller | | `unsafe { ... }` | the author asserts the preconditions inside are met | the block's author | | `unsafe trait` | implementations must keep an extra contract | every implementor | | `unsafe impl` | the implementor asserts the contract holds | the impl's author | | `static mut` | any access may race or alias | every block that touches it | The Reference describes this as two roles: some positions *create* an obligation (`unsafe fn`, `unsafe trait`) and others *discharge* one (`unsafe {}`, `unsafe impl`). ## Why the list is kept short - **Auditing.** Undefined behaviour can only arise through one of those operations, so when memory safety breaks, the search starts at the `unsafe` blocks and the invariants they rely on. - **Small blocks.** Because the rest of the language stays checked, the advice is to keep each block to the one operation that needs it, with a comment saying why it is sound. - **Safe wrappers.** Most of std, from `Vec` to `split_at_mut`, is built on unsafe code behind safe functions, so callers never write `unsafe` themselves. - **Not "dangerous code".** An `unsafe` block is not a claim that the code is buggy; it is a claim that the author checked conditions the compiler could not. Getting one of those conditions wrong is what leads to undefined behaviour, which the lesson on undefined behaviour and Miri covers in detail.

  • Does wrapping slice indexing in `unsafe { }` remove its bounds check and make it faster?
    No. `v[i]` inside an `unsafe` block is checked and panics exactly as outside it, and rustc warns ``unnecessary `unsafe` block`` because indexing is not an unsafe operation. To skip the check you call a different API, `slice::get_unchecked`, which is an `unsafe fn` whose precondition is that the index is in bounds.
  • Is writing to a union field unsafe as well as reading one?
    No. The Reference makes union field access unsafe "other than to assign to it": `u.f = 1.0` compiles in safe code, while `let bits = u.i` fails with E0133, `access to union field is unsafe and requires unsafe block`. Reading assumes the stored bytes are valid for that field's type, which the compiler cannot know.
  • Is every method on a raw pointer unsafe to call?
    No. Methods that only inspect or compute an address, such as `is_null`, `wrapping_add` and casts with `as`, are safe. Methods whose contract assumes the pointer is valid or in bounds, such as `add`, `read`, `write` and `as_ref`, are declared `unsafe fn` and need an unsafe block.

  • An unsafe block turns off the borrow checker for its body.
  • Code inside unsafe is not type-checked, so any cast is allowed.
  • Indexing a slice inside unsafe skips the bounds check.
  • Creating a raw pointer already requires an unsafe block.
  • Writing unsafe means the author admits the code is buggy.
open as a page

In Rust, why does `let p = &raw mut x;` compile in safe code while `*p += 1;` fails with E0133?

level: middleimportance: must knowfreq 62%

basics

~20 s

Creating a raw pointer is harmless: it is only an address and may be null, dangling or aliased. Dereferencing it can touch invalid memory, so only the dereference, and pointer methods such as add or read, need an unsafe block.

open as a page

In Rust 2024, why does an `unsafe fn` that dereferences a raw pointer without an inner `unsafe` block compile only with a warning?

level: middleimportance: should knowfreq 48%

basics

~20 s

Since the 2024 edition the body of an unsafe fn is no longer an unsafe context: the unsafe_op_in_unsafe_fn lint warns on each unsafe operation there. The fix is an explicit unsafe block with a SAFETY comment citing the caller's contract.

open as a page

In Rust 2024, why does `println!("{}", COUNTER)` on a `static mut COUNTER: u32` fail to compile while `COUNTER += 1` in the same unsafe block compiles?

level: seniorimportance: should knowfreq 42%

basics

~20 s

println! borrows its arguments, so it creates a shared reference to the static mut, which the static_mut_refs lint denies by default on edition 2024. COUNTER += 1 writes the place directly and creates no reference.

open as a page

In Rust, what does declaring an `unsafe trait` promise, and why may unsafe code trust an `unsafe impl` but not a safe trait's impl?

level: seniorimportance: should knowfreq 35%

basics

~20 s

An unsafe trait says every implementation upholds a condition the compiler cannot check, signed with unsafe impl. Unsafe code may rely on that promise; a safe trait's impl may be wrong, so relying on it must never risk undefined behaviour.

open as a page