Skip to Content
Course content

197: Raw Pointers in Depth

Click on the "Edit" button in the top corner of the screen to edit your slide content.

When do I actually need a raw pointer instead of just using a reference or a smart pointer?

In 99% of your Rust code, you won't. References are safer and smart pointers like Box or Arc handle the heavy lifting for you. But you'll hit a wall when you start doing FFI (Foreign Function Interface) to talk to C libraries, or when you're building the very data structures that those smart pointers are built upon.

Take a doubly linked list, for example. If you try to build one using standard references, you'll fight the borrow checker until you're blue in the face because you have multiple mutable paths to the same data. Raw pointers (*const T and *mut T) let you sidestep the borrow checker entirely. I usually tell people to view raw pointers as "trust me, I know what I'm doing" pointers. You're telling Rust, "Stop tracking this for a second; I'll handle the memory safety myself."

If I can't dereference them without unsafe, what's the point of creating them?

This is a common point of confusion. Here is the key: creating a raw pointer is perfectly safe. Dereferencing it is where the danger lies.

You can cast a reference to a raw pointer anywhere in your code without an unsafe block. This allows you to pass pointers around, store them in structs, or perform pointer arithmetic without needing to wrap your entire architecture in unsafe. You only enter the "danger zone" when you actually want to read or write the value at that address.

let mut value = 42;
let raw_ptr = &mut value as *mut i32; // This is safe!

unsafe {
    // This is where the risk is. Is raw_ptr still valid? 
    // Does it point to null? Rust doesn't know, and neither does the compiler.
    *raw_ptr = 100; 
}

By separating creation from usage, Rust forces you to explicitly mark the exact line where memory safety is no longer guaranteed, making it much easier to audit your code when things inevitably crash.

How do I handle pointer arithmetic and nulls without crashing?

Unlike references, raw pointers can be null. If you're interfacing with a C API, you'll see std::ptr::null() and std::ptr::null_mut() everywhere. You should always check for null before dereferencing, or use the .as_ref() method which converts a raw pointer into an Option<T>.

As for arithmetic, you can use the .offset() or .add() methods. But be careful—stepping outside the bounds of your allocated memory is an immediate trip to Undefined Behavior (UB) town. I prefer .offset() when I'm dealing with buffers where I know the exact stride of the data.

let array = [10, 20, 30, 40];
let ptr = array.as_ptr();

unsafe {
    // Move the pointer forward by 2 elements
    let third_element = ptr.add(2); 
    println!("The third element is: {}", *third_element); // 30
}

Just remember: add() and offset() don't check bounds. If you add 10 to a pointer pointing to a 4-element array, Rust won't stop you, but your OS probably will with a segmentation fault.




📋 Practical Task

Build a Manual Memory Buffer Offset Reader

Your task is to create a small utility that simulates reading a structured binary packet from a raw memory buffer. This will force you to practice pointer creation, arithmetic, and unsafe dereferencing.

  • Create a byte array [u8; 12] containing some dummy data.
  • Create a raw pointer to the start of this array.
  • Using unsafe, implement a function read_u32_at(ptr: *const u8, offset: usize) -> u32.
  • Inside that function, use .add(offset) to move the pointer and then cast the resulting *const u8 to a *const u32.
  • Dereference the pointer to return the u32 value.
  • Call this function twice to read two different 4-byte integers from your 12-byte buffer.

Hint: You'll need to use as *const u32 to cast the pointer before dereferencing it to read 4 bytes at once.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.