In Rust, why does `let p = &raw mut x;` compile in safe code while `*p += 1;` fails with E0133?
answer
- an address alone harms nobody
- null, dangling, aliased allowed
- the danger starts at use
- add is unsafe, wrapping_add is not
basics
~20 sCreating 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.
solid answer
~40 s`*const T` and `*mut T` carry none of a reference's guarantees: they may be null, dangling or aliased by other pointers, and they free nothing when dropped. So producing one is safe: `&raw const x` and `&raw mut x` (stable since Rust 1.82), casting `&mut x as *mut i32`, even `0x1234usize as *const i32`; so are `is_null`, comparison and `wrapping_add`. The risk begins at use. `*p` fails with E0133, `dereference of raw pointer is unsafe and requires unsafe block`, and the methods that assume a valid or in-bounds pointer, such as `add`, `read`, `write` and `as_ref`, are `unsafe fn`. Prefer `&raw mut` to casting a reference where creating the reference is itself wrong, as with a `static mut` in the 2024 edition.
code
rust · 7 linesfn main() {
let mut x = 5;
let p = &raw mut x; // safe: just an address
let q = 0x1234usize as *const i32; // safe: never dereferenced
let _ = q;
*p += 1; // error[E0133]
}go deeper
Say that making a raw pointer is safe and dereferencing it needs unsafe, and name the two types, *const T and *mut T.
List what a raw pointer gives up compared with a reference, and sort pointer methods into safe address arithmetic and unsafe fns that assume validity.
Know why &raw mut beats casting a reference for statics and packed fields, and review an unsafe block by checking the precondition of each pointer method it calls.
Use the create-safe, use-unsafe split to keep pointer plumbing out of unsafe blocks, so the audited surface is only the lines that touch memory.
## Two pointer types without guarantees Rust has two **raw pointer** types: `*const T` and `*mut T`. The asterisk is part of the type name, not the dereference operator. A raw pointer is an address (plus, for slices and trait objects, metadata) and nothing more. Unlike a reference `&T` or `&mut T`, a raw pointer: - **may be null**, which a reference never is; - **may dangle**, pointing at memory that was freed or never allocated; - **ignores the borrow rules**, so a `*const T` and a `*mut T`, or two `*mut T`, may point at one place at the same time; - **runs no cleanup**: dropping a raw pointer frees nothing. Because a raw pointer promises none of this, holding one cannot hurt anybody. The harm can only start when the program uses the pointer to touch memory. ## Creating is safe, dereferencing is not That is exactly where Rust draws the line. All of these compile in safe code: - `&raw const x` and `&raw mut x`, the raw borrow operators stabilised in **Rust 1.82**; - casting a reference, `&mut x as *mut i32`; - casting an integer, `0x1234usize as *const i32`, which points nowhere sensible; - `p.is_null()`, `p == q`, and `p.wrapping_add(100)`, even when the result leaves the allocation. What needs an `unsafe` block is any operation that relies on the pointer being valid: | Operation | Safe code? | Why | |---|---|---| | `&raw mut x`, `&mut x as *mut T` | yes | only an address is produced | | `p.is_null()`, `p.wrapping_add(n)` | yes | pure address arithmetic | | `*p`, `*p = v` | no, E0133 | reads or writes memory | | `p.read()`, `p.write(v)`, `p.as_ref()` | no, `unsafe fn` | assumes valid, aligned memory | | `p.add(n)` | no, `unsafe fn` | result must stay inside one allocation | The compiler's message for the bare dereference is `error[E0133]: dereference of raw pointer is unsafe and requires unsafe block`, with a note that "raw pointers may be null, dangling or unaligned". For `add`, std's documentation states that the whole range between the pointer and the result must be in bounds of one allocation, with one-past-the-end allowed; `wrapping_add` has no such precondition, which is why it is a safe method. One subtlety: `&raw const (*p).len` is rejected without `unsafe` even though nothing is read, because naming the field goes through `*p`, and dereferencing a raw pointer as a place is itself the unsafe operation. ## Raw borrow versus casting a reference `&mut x as *mut i32` first creates a `&mut i32` and then turns it into a pointer. Usually that is harmless, but sometimes creating the reference is the problem. A reference to a `static mut` is a deny-by-default lint error in the 2024 edition, and a reference to a field of a `repr(packed)` struct is rejected with E0793 because it may be unaligned. `&raw mut x` produces the pointer without an intermediate reference, so it works in both places. Before 1.82 the same thing was spelled with the macros `ptr::addr_of!` and `ptr::addr_of_mut!` (stable since 1.51), which still exist. ## Reading the ring buffer The code example is a fixed-capacity ring buffer that writes into its own boxed slice through raw pointers. A reviewer new to unsafe should check it in this order: 1. **Find the unsafe blocks.** There are two, each holding a single `add` plus a `write` or `read`. Getting `base` from `as_mut_ptr` and `as_ptr` sits outside them, because it is safe. 2. **Read the SAFETY comment.** It names the condition `add` requires, that the index is below the slice length, and the reason it holds. 3. **Check the reason.** `tail` is reduced `% cap`; `head` is only ever assigned a value reduced `% self.buf.len()`, so both stay in bounds. 4. **Check aliasing.** No `&` or `&mut` into `buf` is alive while the pointer is used, so writing through `*mut` conflicts with nothing. The program prints `Some(2) Some(3) None`, and `cargo miri run` reports no undefined behaviour for it. A clean run is evidence for this input, not a proof; the proof is the argument in each SAFETY comment. ## Why the split helps Keeping creation safe means pointer plumbing, such as storing a `*mut T` in a struct, comparing pointers or passing them to C, needs no `unsafe` at all. Only the few lines that actually touch memory carry the keyword, so a reviewer's attention goes exactly where the risk is.
- Why is `&raw const (*p).len` rejected without `unsafe` even though nothing is read?Because the place `(*p).len` is reached by dereferencing the raw pointer `p`, and dereferencing a raw pointer is the unsafe operation even when the result only feeds another raw borrow. rustc reports E0133, `dereference of raw pointer is unsafe and requires unsafe block`. `&raw const` of a local or a static involves no dereference and is safe.
- In Rust, is computing `p.wrapping_add(100)` past the end of an allocation already a problem?No. `wrapping_add` is a safe method and may produce an address outside the allocation; std only requires that such a pointer is not dereferenced while out of bounds. `add` is different: its own contract requires the result to stay inside one allocation (one past the end counts), which is why it is an `unsafe fn`.
- Turning a reference into a raw pointer needs an unsafe block.
- Two *mut pointers to one value fail to compile like two &mut.
- ptr.add(n) is safe because it is only arithmetic.
- &mut x as *mut i32 and &raw mut x are interchangeable everywhere.
- Dropping a raw pointer frees the memory it points to.
Assumes Rust 1.99 on edition 2024; the &raw const and &raw mut operators are stable since Rust 1.82, and older code uses ptr::addr_of! for the same thing.