skip to content

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%

answer

  1. two jobs, one keyword
  2. caller's promise, not a free pass
  3. a lint that changed default
  4. SAFETY comment per block

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.

solid answer

~40 s

`unsafe fn` declares that callers must uphold conditions the compiler cannot check; an `unsafe` block asserts that the conditions inside it are met. Until edition 2021 the keyword on a function also made its body unsafe, so operations slipped in unmarked. On edition 2024 (Rust 1.85 onward) the `unsafe_op_in_unsafe_fn` lint defaults to `warn`, so rustc prints `warning[E0133]: dereference of raw pointer is unsafe and requires unsafe block` with the note that the body is safe by default. It stays a warning unless the crate denies the lint. The fix wraps just the operation in `unsafe { }` with a `// SAFETY:` comment pointing at the caller's promise, and the function's docs get a `# Safety` section, which clippy's `missing_safety_doc` checks for `pub unsafe fn`.

code

rust · 9 lines
rust
unsafe fn read_at(p: *const u8, i: usize) -> u8 {
    *p.add(i) // edition 2024: warning[E0133], twice
}

fn main() {
    let b = [1u8, 2, 3];
    let v = unsafe { read_at(b.as_ptr(), 1) };
    println!("{v}");
}

go deeper

for a junior

Know that calling an unsafe fn needs an unsafe block and that its documentation lists what the caller must guarantee.

for a middle

Explain the two roles, creating an obligation versus discharging one, and what unsafe_op_in_unsafe_fn changed in the 2024 edition.

for a senior

Write # Safety sections and SAFETY comments that name each precondition, and decide when a checked safe function beats an unchecked unsafe one.

for a principal

Decide which unsafe lints a codebase raises, such as deny unsafe_op_in_unsafe_fn or the clippy restriction lints, and what review expects of every SAFETY comment.

## One keyword, two jobs In Rust, `unsafe` on a function and `unsafe` on a block mean opposite things. The Reference calls them **duals**: | Form | What it says | Who does the work | |---|---|---| | `unsafe fn f()` | calling `f` has extra conditions the compiler cannot check | every caller, inside its own `unsafe` block | | `unsafe { ... }` | the conditions of the operations inside are met here | the author of the block | So an `unsafe fn` *creates* an obligation for its callers, and an `unsafe` block *discharges* the obligations of what it contains. Calling `read_at` without a block fails with E0133, ``call to unsafe function `read_at` is unsafe and requires unsafe block``. Before the 2024 edition, the keyword on a function also made its whole body an unsafe context. That mixed the two jobs: writing `unsafe fn` to warn callers silently allowed every unsafe operation in the body, with no block marking where each one was and no place to say why it was sound. ## What the 2024 edition changed The lint `unsafe_op_in_unsafe_fn` separates the jobs. Its default is `allow` on editions before 2024 and **`warn` on the 2024 edition** (stable since Rust 1.85, current in 1.99). The body of an `unsafe fn` is now treated as safe code, and each unsafe operation in it needs its own block. Compiling the first code example on rustc 1.99.1 with `--edition 2024` gives two warnings, both labelled `warning[E0133]`: one for `dereference of raw pointer`, one for `call to unsafe function` (the `add` method). rustc adds the note `an unsafe function restricts its caller, but its body is safe by default`. With `--edition 2021` the same file compiles silently. Facts worth stating precisely in an interview: - It is a **warning**, not an error; the program still builds, unless the crate raises the lint with `#![deny(unsafe_op_in_unsafe_fn)]`. - The lint belongs to the `rust-2024-compatibility` group, and `cargo fix --edition` inserts the missing blocks during migration. - The fix is mechanical: wrap only the operation, `unsafe { *p.add(i) }`, and leave safe statements outside. Why the change was worth an edition: - **Visibility.** Every unsafe operation in an `unsafe fn` now sits in a block a reviewer can find, instead of hiding in a body that was unsafe as a whole. - **Room for a reason.** Each block can carry its own `SAFETY` comment, so the argument sits beside the operation it justifies. - **Smaller blocks.** The rest of the body is checked like any safe code, so a stray dereference added later is flagged instead of silently accepted. ## Writing the contract down The keyword says *that* there is a contract; prose says *what* it is. The conventions: 1. **A `# Safety` section** in the doc comment of every `unsafe fn` lists the caller's obligations. Clippy's `missing_safety_doc` lint, in the default `clippy::style` group, warns when a `pub unsafe fn` lacks one. 2. **A `// SAFETY:` comment** directly above each `unsafe` block says why each obligation holds at that point. Inside an `unsafe fn` the reason is often the function's own contract: "the caller promises `i < len`". 3. **Enforcement**, if a team wants it: `clippy::undocumented_unsafe_blocks` warns on an `unsafe` block with no `SAFETY` comment. It is a `clippy::restriction` lint, allowed by default, so it must be enabled explicitly. `clippy::multiple_unsafe_ops_per_block`, also a restriction lint, pushes toward one operation per block. Running `cargo clippy` on the second code example produces no warning. Removing the `# Safety` section yields ``unsafe function's docs are missing a `# Safety` section``; removing a `SAFETY` comment yields `unsafe block missing a safety comment`. ## Choosing between them - Make a function `unsafe fn` only when its correctness depends on a condition the function cannot check itself, such as an index the caller promises is in range. - If the function can check the condition cheaply, check it and keep the function safe: `slot` with an `assert!` or a `get` returning `Option` beats `slot_unchecked` for most callers. - Offer the unchecked variant next to the checked one when a hot path has already proved the condition, as std does with `get` and `get_unchecked`. - Never mark a function `unsafe` just because its body contains unsafe code; a safe function wrapping a justified block is the normal shape, as `first` shows. Whether such a safe wrapper is truly sound for every possible caller is the subject of the lesson on sound safe abstractions.

  • Inside an `unsafe fn`, what can a `SAFETY` comment cite when the body has no local check?
    The function's own contract. The `# Safety` section states what every caller must guarantee, so the block inside can say, for example, "the caller promises `i < self.buf.len()`". That is the Reference's point that an unsafe block may discharge its obligations using the proof obligations of the enclosing `unsafe fn`.
  • How does a crate make the 2024 behaviour an error rather than a warning?
    Raise the lint level, for instance with `#![deny(unsafe_op_in_unsafe_fn)]` at the crate root, or in the `[lints]` table of the manifest. The same attribute with `warn` lets a crate on edition 2021 adopt the new behaviour before migrating.

  • In Rust 2024 an unsafe fn body is still one big unsafe block.
  • Leaving out the inner block is a hard error on edition 2024.
  • A function containing unsafe code must itself be marked unsafe fn.
  • Calling an unsafe fn is fine without unsafe if it has docs.
  • clippy::undocumented_unsafe_blocks is on by default.

Assumes Rust 1.99 on edition 2024; unsafe_op_in_unsafe_fn warns by default only on the 2024 edition (Rust 1.85 onward) and is allowed by default on earlier editions.