In Rust, &mut
aliasing causes undefined behavior. But what happens in the case of pointers and references, as shown below?
<code>fn main() {
let mut data = 12345;
let p = &mut data as *mut _;
let r = &mut data;
println!("r = {}", r);
unsafe {
*p = 54321; // <- Is this UB?
}
println!("r = {}", r);
}
</code>
<code>fn main() {
let mut data = 12345;
let p = &mut data as *mut _;
let r = &mut data;
println!("r = {}", r);
unsafe {
*p = 54321; // <- Is this UB?
}
println!("r = {}", r);
}
</code>
fn main() {
let mut data = 12345;
let p = &mut data as *mut _;
let r = &mut data;
println!("r = {}", r);
unsafe {
*p = 54321; // <- Is this UB?
}
println!("r = {}", r);
}
Playground
Similar question
Here is a very similar question: Do aliasing mutable raw pointers (*mut T) cause undefined behaviour?
According to the answer to this one, it appears that the use of the +=
operator causes UB. However, even after reading this, I could not figure out whether *p =
causes a UB or not.