9

I am rather confused about the following problem. If I understand it correctly

let x = &42; 

is expanded internally to

let x_value = 42; let x = &x; 

I think I have seen this in the Rust book somewhere but I cannot find the reference to it.

My problem is concerning the following code:

let x = 42; let rx = &x; let px = rx as *const i32 as *mut i32; unsafe { *px = 0; } println!("{}", x); 

As expected this prints 0. However, if I write

let rx = &42; let px = rx as *const i32 as *mut i32; unsafe { println!("Deref"); *px = 0; } println!("{}", x); 

the program terminates after printing out Deref. Aparently something goes wrong when px gets dereferenced. I guess my first assessment about let x = &42 getting expanded internally is wrong.

2 Answers 2

12

You're invoking undefined behavior. From the Rust Reference:

12.3 Behavior considered undefined

The following is a list of behavior which is forbidden in all Rust code, including within unsafe blocks and unsafe functions. [...]

  • Mutating non-mutable data (that is, data reached through a shared reference or data owned by a let binding), unless that data is contained within an UnsafeCell<U>.

Since you're mutating non-mutable data, you're invoking undefined behavior. The fact that it works at all in the first version is just (bad) luck.

Sign up to request clarification or add additional context in comments.

1 Comment

I looked up the implementation of UnsafeCell<T> and wanted to experiment with raw pointers. The important part I overlooked is the attribute #[lang = "unsafe_cell"]. Thanks.
1
let x = 42; let rx = &x; 

Here you create a new variable on stack and write the value 42 that comes from the code of your program. When creating a reference, it is referencing this value on stack. When you change the value by *px = 0; you gain access to the value on stack and can change it.

In the second case

let rx = &42; 

you create a reference directly to the value stored in the part of memory that stores the code (instructions and other data). And this part of memory is immutable.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.