Raw pointers and validity
Quick answer
Raw pointers such as *const T and *mut T can exist without the guarantees of a reference. Creating one is often safe; dereferencing it requires a valid access for the intended type and operation.
Separate addresses from access
For a nonzero-sized read, the pointer must refer to accessible initialized data, be suitably aligned, carry suitable provenance and respect aliasing rules. A non-null pointer may still be dangling or misaligned. Pointer arithmetic has its own bounds requirements. Prefer references when their lifetime and exclusivity model matches the problem.
fn main() { let n = 12u32; let p = &n as *const u32; // SAFETY: n is live, aligned, initialized; only shared reads occur. println!("{}", unsafe { *p });}Expected stdout (not executed):
12The reference used to create p is valid for this read.
fn main() { let p = std::ptr::null::<u32>(); println!("{}", p.is_null());}Expected stdout (not executed):
trueTesting the pointer does not dereference it. Non-null alone would not prove validity either.
Common mistake
Do not turn arbitrary integer addresses into references.
Try it yourself
Describe which conditions would fail if the allocation holding n were already freed; do not run that case.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Raw pointers and validity — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A raw pointer is non-null but points to a freed allocation. Is reading it allowed?
Raw pointers and validity — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn main() { let n = 12u32; let p = &n as *const u32; // SAFETY: n is live, aligned, initialized; only shared reads occur. println!("{}", unsafe { *p }); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Raw pointers and validity — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn main() { let p = std::ptr::null::<u32>(); println!("{}", p.is_null()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.