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?
CodePudding user response:
This issue can be answered by looking at the different semantics of the both code lines you provided.
fn main() {
let val = 1;
println!("{:?}", val as *const i32); // Output: 0x1
println!("{:?}", &val as *const i32); // Output: 0x7ff7b36a4eec (probably little different)
}
Without the reference the value of the variable is take as it is to be used to dereference the memory. This leads of course to a segmentation fault, since it will be not in the allowed address range of the program.
Only when the reference operator is used, the address of the variable is casted to a raw pointer, which then later can be dereferenced without any segmentation fault.