这段代码会导致定义的行为吗?

mr.*_*lue 2 memory unsafe rust

我正在尝试学习 Rust。我遇到了一个片段。我认为代码中的指针可能是无效引用,但它有效。

fn main() {
   let x={
       let mut y=[3];
       y.as_mut_ptr()
   };
   unsafe {println!("{}",*x);}
}
Run Code Online (Sandbox Code Playgroud)

use*_*968 7

非常快速的回答:这是 UB,很容易。内存在内部块的末尾失效,因此x从创建时起就处于不可取消引用的状态。它似乎按照您的预期执行这一事实是无关紧要的。

以您的示例查看 Playground,然后单击“工具 -> 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
Run Code Online (Sandbox Code Playgroud)