Sub topic 4
Working with raw pointers
This chapter assumes you know ownership, borrowing, slices, and how to build a program with Cargo. It also assumes you know that an unsafe block lets you do a few extra things while the compiler keeps checking everything else.
What a raw pointer is
A raw pointer is an address with a type attached. Rust has two kinds:
*const Tis a pointer you read through.*mut Tis a pointer you may also write through.
The * is part of the type name. It does not mean dereference here.
Raw pointers differ from references (&T and &mut T) in several ways:
| Property | Reference | Raw pointer |
|---|---|---|
| May be null | No | Yes |
| May dangle | No | Yes |
| Borrow checker tracks it | Yes | No |
| Aliasing rules enforced | Yes | No |
| Frees memory on drop | No | No |
| Dereference needs `unsafe` | No | Yes |
Creating and dereferencing
Creating a raw pointer is safe. Dereferencing it is not, because the compiler cannot tell whether the address is valid.
fn main() {
let mut num = 5;
let p = &mut num as *mut i32;
unsafe {
*p += 1;
println!("num through pointer: {}", *p);
}
}The cast &mut num as *mut i32 ends the borrow as far as the compiler is concerned. After that, nothing stops you from keeping the pointer after num is gone.
Pointer arithmetic
Pointers move in units of T, not bytes. ptr.add(n) advances by n elements, so for a *const u32 it moves 4 * n bytes. The result must stay inside the same allocated object, or one element past its end. Going beyond that is undefined behavior, even if you never dereference the result.
fn main() {
let values = [10, 20, 30];
let start = values.as_ptr();
for i in 0..values.len() {
// SAFETY: `i < len`, so `start.add(i)` stays inside `values`,
// which is alive and fully initialized.
let v = unsafe { *start.add(i) };
println!("{v}");
}
}The methods read and write copy a value in or out through a pointer. They do not run drop on the old value, so use them carefully with types that own resources.
Common mistakes
- Dangling pointers. A pointer to a local variable stays creatable after the function returns, but dereferencing it is undefined behavior. The compiler gives no warning.
- Forgetting null. Pointers from foreign code or
std::ptr::null()can be null. Check withp.is_null()before dereferencing, or usep.as_ref(), which returnsOption<&T>. Callingas_refis itself unsafe, because it creates a reference and you must guarantee the pointer is valid. - Out-of-bounds arithmetic.
addhas no bounds check. Compare the index with the length first. - Misalignment. A
*const u32must hold an address divisible by 4. Casting a byte pointer to*const u32at an odd offset gives a misaligned pointer. Useread_unalignedfor that case. - Turning a pointer into a reference too early.
&*por&mut *passerts that all reference rules hold for as long as the reference lives. Two live&mutreferences to the same data break those rules, even if the code looks harmless.
Checklist for each dereference
Before every unsafe { *p }, write down why the pointer is non-null, aligned, pointing to live initialized memory, and free of conflicting access. Put this reasoning in a // SAFETY: comment. If you cannot write that comment, the code is not ready.
Exercise
A function returns &local as *const i32, where local is a variable declared inside that function. The caller dereferences the pointer in an unsafe block. Which rule is broken, and why does the code still compile?
Show answer
The pointer dangles, because local was dropped when the function returned, so the caller reads memory that is no longer a live i32. That is undefined behavior. It compiles because creating a raw pointer is safe and the borrow checker does not track raw pointers, so the lifetime error that a reference would cause is never reported.
Exercise
You have let p: *const u8 = bytes.as_ptr(); for a [u8; 8] array. Why is unsafe { *(p.add(1) as *const u32) } risky, and which method would be a safer choice?
Show answer
The address p.add(1) is probably not aligned to 4 bytes, and a normal dereference of a misaligned *const u32 is undefined behavior. (p.add(1) as *const u32).read_unaligned() is the correct choice, and the pointer must still point to at least 4 valid bytes.