Course contentsShow
← Rust
Lesson 248 of 1,9103. Borrowing and ReferencesFree lesson

Dereferencing Raw Pointers

Follow strict safety protocols when converting raw pointers back to references.

Dereferencing Raw Pointers

In this lesson, you will learn the strictly controlled process of converting a raw pointer back into a usable Rust reference.

When you work with raw pointers (*const T or *mut T), Rust turns off its safety guardrails because it no longer knows if the memory address is valid or if it’s currently being modified by someone else. To use the data these pointers point to, you must "dereference" them, which requires an unsafe block.

The Safety Protocol

Dereferencing is not just about accessing data; it is an assertion you make to the compiler. Because the compiler can no longer guarantee safety, you must personally ensure three things before dereferencing:

  1. Validity: The pointer must point to allocated, initialized memory.
  2. Alignment: The pointer must point to an address that is properly aligned for the type T.
  3. Aliasing: There must not be any other active mutable references to this memory.

If you violate these, you trigger Undefined Behavior, which is the most dangerous state in Rust.

How to Dereference

You dereference a raw pointer using the * operator, just like you would with a smart pointer or a standard reference. However, it must be inside an unsafe block:

let my_num = 10;
let ptr = &my_num as *const i32;

unsafe {
    // Dereferencing the raw pointer to read the value
    let val = *ptr;
    println!("The value is: {}", val);
}

When you dereference a *mut T, you can also create a mutable reference, but you must be extremely careful. By turning a raw pointer into a reference (&*ptr or &mut *ptr), you are effectively telling the compiler: "I have manually checked that this memory is safe to use as a reference."

The goal is to keep your unsafe block as tiny as possible—ideally, only the single line where you dereference—so that you can quickly wrap the raw data back into a safe, standard Rust reference. From that point on, the borrow checker takes over again, keeping your code safe.

Key Takeaway: Dereferencing raw pointers is an explicit promise to the compiler that the pointer is valid, aligned, and properly aliased; always perform this in the smallest possible unsafe scope.