小编Tur*_*ton的帖子

为什么在使用不安全的Rust访问超出范围的变量时没有段错误?

我在玩不安全的Rust时遇到了这种奇怪的现象.我认为这段代码应该会出现分段错误,但事实并非如此.我错过了什么吗?我试图设置一个指向一个生命周期较短的变量的指针,然后取消引用它.

// function that sets a pointer to a variable with a shorter lifetime
unsafe fn what(p: &mut *const i32) {
    let a = 2;
    *p = &a;
    //let addr = *p;    // I will talk about this later
    println!("inside: {}", **p);
}

fn main() {
    let mut p: *const i32 = 0 as *const i32;
    unsafe {
        what(&mut p);

        // I thought this line would make a segfault because 'a' goes out of scope at the end of the …
Run Code Online (Sandbox Code Playgroud)

memory unsafe unsafe-pointers rust

2
推荐指数
1
解决办法
130
查看次数

标签 统计

memory ×1

rust ×1

unsafe ×1

unsafe-pointers ×1