Dereference raw pointer - unsafe code

I thought that to use raw pointer we must use unsafe keyword.
However this code allows dereference raw pointer without unsafe keyword:

q: why can you dereference raw pointer without unsafe code?
fn main(){
     let foo: u8 = 123;
    // get a reference to the value
    let foo_ref = &foo;
    // convert the reference to a raw pointer
    let foo_raw_ptr = foo_ref as *const u8;
    // convert the raw pointer to an integer
    let foo_addr = foo_raw_ptr as usize;

    println!("'foo' address = {:X}", foo_addr);
}

This code doesn't ever dereference the pointer, i.e. read from the memory location that the pointer refers to. Instead, it just prints where that memory location is.

2 Likes

That is because an usize does not hurt anyone. You can't do harm with a number. The unsafe part starts when you start turning that back into a pointer you can access memory with.

By the way, you can print the address of a pointer like this without going through usize:

println!("'foo' address = {:p}", foo_ref as *const u8):

This likewise does not dereference the pointer.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.