Running the following code gives a segmentation fault:
fn main() {
let val = 1;
let ptr = val as *const i32;
unsafe { println!("{:?}", *ptr) };
}
Output:
[1] 69212 segmentation fault (core dumped) cargo r
However, when val is put in as a reference & while declaring the raw pointer, the code runs as intended and as val is printed out.
fn main() {
let val = 1;
let ptr = &val as *const i32;
unsafe { println!("{:?}", *ptr) };
}
Output:
1
So what is the shared reference doing here and why does the program fail without it? Isn't a reference in rust also a pointer with extra schematics? Why to we need to create a pointer to a reference and not directly to the val itself?