Sub topic 4
Working with raw pointers
This chapter assumes you know ownership, borrowing, slices, and structs in safe Rust. It also assumes you have read the earlier chapters on what unsafe allows and what undefined behavior (UB) is. Examples use Rust 2024 and run with cargo run.
What a raw pointer is
A raw pointer is a value that holds a memory address. Rust has two types:
*const Tis a pointer you may read through.*mut Tis a pointer you may read and write through.
The * is part of the type name. It is not a dereference here.
A raw pointer differs from a reference in these ways:
| Property | Reference (`&T`, `&mut T`) | Raw pointer (`*const T`, `*mut T`) |
|---|---|---|
| Can be null | No | Yes |
| Borrow checker tracks it | Yes | No |
| Has a lifetime | Yes | No |
| Can alias a `&mut` | No | Yes, but see the aliasing rules below |
| Must be valid when created | Yes | No |
| Dropped or freed automatically | The referent is owned elsewhere | The pointee is never dropped through the pointer |
| Implements `Copy` | `&T` only | Always |
A reference promises the compiler that the memory is valid. A raw pointer promises nothing. That is why you can create one in safe code, but you need unsafe to use it.
Creating raw pointers
Creating a raw pointer is safe, because an address does nothing until you use it.
use std::ptr;
fn main() {
let mut value = 10i32;
let a: *const i32 = &value; // coercion from &i32
let b: *mut i32 = &mut value; // coercion from &mut i32
let c = &raw const value; // no intermediate reference
let d = &raw mut value;
let nothing: *const i32 = ptr::null(); // address 0
println!("{}", a == c.cast::<i32>());
println!("{}", ptr::eq(b, d));
println!("{}", nothing.is_null());
}Use &raw const and &raw mut when you need a pointer to a place that may be misaligned or uninitialized. Writing &value as *const _ creates a real reference first, and a reference to such a place is itself UB. Use .cast::<U>() to change the pointee type. It cannot change mutability by accident the way an as cast can.
Dereferencing and the validity checklist
Dereferencing a raw pointer with *p is the first of the five unsafe operations. Before you dereference, you must be able to justify every item below.
- The pointer is non-null.
- It points into a single allocated object that is still alive.
- The whole range you access lies inside that object.
- The address is aligned for
T. - The memory holds a valid, initialized
T, for reads. - No other thread accesses it at the same time without synchronization.
- Creating a reference from it does not break the aliasing rules.
The first example mutates an array through a pointer.
fn main() {
let mut data = [10u32, 20, 30, 40];
let len = data.len();
let start = data.as_mut_ptr();
for i in 0..len {
// SAFETY: `i < len`, so `start.add(i)` stays inside `data`,
// which is alive, aligned, and initialized.
unsafe {
*start.add(i) += 1;
}
}
println!("{data:?}");
}The code reads len before taking the pointer. Calling data.len() while start is in use would create a fresh reference to the array. Tools like Miri can treat that as invalidating the pointer.
Pointer arithmetic
Pointer arithmetic moves a pointer in units of T, not bytes.
p.add(n)andp.sub(n)move forward or back bynelements.p.offset(n)takes a signedisize.p.offset_from(q)returns the distance in elements between two pointers.p.byte_add(n)moves by bytes.
The methods add, sub, and offset are unsafe. The result must stay in bounds of the same allocation, or exactly one element past its end. You may form that one-past-the-end pointer, but you may not dereference it. Going further out is UB even if you never dereference the result.
If you need arithmetic without that guarantee, use wrapping_add, wrapping_sub, or wrapping_offset. These are safe, and they never cause UB themselves. A pointer they produce is still only usable if it lands inside the original allocation.
Casting a pointer to an integer with as usize is safe. Casting an integer back to a pointer gives you a pointer that may have lost its link to the original allocation. Prefer the with_addr and map_addr methods when you must change an address and keep that link.
Reading and writing
Writing *p = value drops the old value at p first. If that memory is uninitialized, the drop runs on garbage. To avoid that, use the functions that move bytes without dropping:
p.read()copies the value out bitwise. It does not run any code on the source.p.write(v)storesvand does not drop what was there.p.read_unaligned()andp.write_unaligned(v)work on misaligned addresses.p.replace(v)andptr::swap(a, b)exchange values.
The next example swaps two Strings by hand. It shows why read and write exist.
fn main() {
let mut a = String::from("left");
let mut b = String::from("right");
let pa: *mut String = &mut a;
let pb: *mut String = &mut b;
// SAFETY: `pa` and `pb` point to two distinct, live, aligned, initialized
// Strings. `read` makes a bitwise copy, and each location is overwritten
// with `write` (which does not drop) before anything is dropped, so every
// String has exactly one owner at the end.
unsafe {
let tmp = pa.read();
pa.write(pb.read());
pb.write(tmp);
}
println!("{a} {b}");
}The program prints right left. If you replaced pa.write(...) with *pa = ..., the old string would be dropped while tmp still owns the same buffer, and the buffer would be freed twice.
For misaligned data, use the unaligned variants. A *const u32 that is not 4-byte aligned must not be dereferenced.
fn main() {
let bytes: [u8; 5] = [0, 1, 0, 0, 0];
// SAFETY: offset 1 plus 4 bytes is 5, which is within the 5-byte array.
let p = unsafe { bytes.as_ptr().add(1) } as *const u32;
// SAFETY: the 4 bytes at `p` are in bounds and initialized. They may be
// misaligned for u32, so we use `read_unaligned`.
let raw = unsafe { p.read_unaligned() };
println!("{}", u32::from_le(raw));
}This prints 1.
Checking for null
A pointer may be null, so check it before use. as_ref and as_mut turn a pointer into an Option of a reference. They return None for null.
use std::ptr;
fn main() {
let x = 5i32;
let good: *const i32 = &x;
let none: *const i32 = ptr::null();
// SAFETY: `good` points to the live, initialized `x`. `none` is null,
// so `as_ref` returns `None` without touching memory.
unsafe {
println!("{:?}", good.as_ref());
println!("{:?}", none.as_ref());
}
}as_ref is still unsafe because a non-null pointer must also be valid, aligned, and not mutably aliased for the whole life of the reference it returns. It checks null and nothing else.
Common errors
Dangling pointers
A pointer is dangling when its target has been freed, moved, or gone out of scope. The compiler will not stop you.
fn main() {
let mut v = vec![1, 2, 3];
let p = v.as_ptr();
v.push(4); // may reallocate, so `p` may now point to freed memory
// Reading `*p` here would be undefined behavior.
// Take a new pointer after the push instead.
let fresh = v.as_ptr();
// SAFETY: `fresh` was taken after the last mutation and `v` is non-empty.
println!("{}", unsafe { *fresh });
let _ = p;
}Breaking aliasing rules
Rust assumes a live &mut T is the only way to reach its target. Suppose you turn a raw pointer into a &mut while another reference or a pointer-derived access is still in use. The compiler may then optimize on an assumption that no longer holds. Keep references created from raw pointers short-lived, and prefer working through the pointer directly.
Casting to a stricter type
Casting *const u8 to *const u32 is safe, and it does not change the address. Dereferencing the result needs the address to be 4-byte aligned. This fails on some platforms by crashing and on others by silently misbehaving. Use read_unaligned when you cannot prove alignment.
Treating a pointer as ownership
A raw pointer does not free its target. Memory from Box::into_raw leaks unless you call Box::from_raw exactly once. Calling it twice causes a double free.
Exercises
Exercise
What is wrong with *p = String::from("new"); when p: *mut String points to uninitialized memory, and what should you write instead?
Show answer
Assignment through a pointer first drops the old value at p. With uninitialized memory, that runs the destructor on garbage, which is undefined behavior. Use p.write(String::from("new")) (or ptr::write(p, ...)), which stores the value without dropping what was there.
Exercise
You have let p = v.as_ptr(); for a Vec<i32> v with 3 elements. Which of p.add(2), p.add(3), and p.add(4) may you compute, and which may you dereference?
Show answer
p.add(2) and p.add(3) may be computed. The result of add(3) is one past the end, which is allowed as long as the pointer stays in bounds of the allocation in use. Only p.add(2) may be dereferenced, because p.add(3) points past the last element. p.add(4) is UB to compute with add, even if you never dereference it, because it goes beyond one-past-the-end. Use wrapping_add if you need the address without that rule.