`unsafe` and raw pointers
*const T and *mut T are raw pointers. They may be null, they do not borrow-check, and dereferencing them is unsafe. They are the FFI and allocator vocabulary.
Detailed Explanation
A reference is a proven-valid pointer. A raw pointer is an address. You can create one in safe code: &x as *const i32, std::ptr::null(), Box::into_raw. You cannot dereference it in safe code. unsafe { *p } is the read. unsafe { *p = v } is the write. You must guarantee that p is aligned, non-null (unless T is zero-sized), pointing at a live T, and not violating aliasing (noalias) rules.
Raw pointers do not extend lifetimes. A *const T derived from a local is just a number after the local dies. The compiler will not stop you from keeping it. That is the entire unsafety. offset and add do pointer arithmetic, like C, and going out of the allocation is UB.
You need raw pointers to call C, to write a custom Vec, to build an intrusive list, to do provenance-aware tricks with std::ptr. You do not need them to pass a slice to a function: &[T] is the safe fat pointer. Wrapping a raw pointer in a safe type (struct Unique<T>(*mut T) plus Drop) is the usual design: the unsafe is small and documented, the rest of the crate is safe.
Send and Sync are not implemented for raw pointers. A struct that contains one is not auto-Send. That is why people write mistaken unsafe impl Send and invent data races. If the pointer is to thread-shared unsynchronised memory, do not implement Send.
When you write *mut T: FFI, allocators, and proven low-level code. When you write &mut T: everything else. When you dereference: one unsafe block, one SAFETY comment that names the invariant.
Code Examples
fn main() {
let mut n = 7;
let p: *mut i32 = &mut n;
unsafe {
*p += 1; // SAFETY: p came from `n`, which is live and uniquely borrowed here.
}
println!("{n}"); // prints: 8
}Common Gotchas
A dangling raw pointer is UB to dereference, not a predictable crash
The optimiser may delete later code. Do not "try" a pointer.
Creating a pointer is safe; using it is not
A safe function that returns `*mut T` shifts the obligation to every caller. Prefer a safe wrapper.
Raw pointers are not `Send`/`Sync` by default
An `unsafe impl` is a claim about the pointee. Most pointees are not ready for that claim.
`offset` must stay in the same allocation
One-past-the-end is allowed for the pointer value; dereferencing it is not.