Skip to main content
1 of 4

Can a language allow raw pointer dereferencing while preserving memory safety?

In rust you can create a pointer safely:

let my_num_ptr: *const i32 = &my_num;

But then dereferencing it is unsafe:

let value: i32 = unsafe {*my_num}

To cause undefined behavior requires both constructing a invalid pointer then de-referencing it. As long as one part is unsafe it should be impossible to read bad memory in only safe code.

So something like:

let i: const *u32 = unsafe {
    &4
};
let b=*i;

Or even:

let i: mut *u32 = unsafe {
   &8;
}
*i=5;

Other pointer operations like casting would also become unsafe. Is this sound? Would there be any advantages to doing it this way instead of the rust way.