Does this code result in defined behaviour?

Viewed 91

I am trying to learn Rust. I come across a snippet. I think the pointer in the code may be invalid reference but it works.

fn main() {
   let x={
       let mut y=[3];
       y.as_mut_ptr()
   };
   unsafe {println!("{}",*x);}
}
1 Answers

Very quick answer: It's UB and easily so. The memory gets invalidated at the end of the inner block, so x is in an un-dereferenceable state from the time it's created. The fact that it appears to do what you expected is irrelevant.

See the playground with your example and click on "Tools -> Miri".

error: Undefined Behavior: pointer to alloc1851 was dereferenced after this allocation got freed
 --> src/main.rs:7:24
  |
7 |         println!("{}", *x);
  |                        ^^ pointer to alloc1851 was dereferenced after this allocation got freed
  |
  = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
  = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
Related