V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
enzo26
V2EX  ›  Rust

double free 为什么不报错?

  •  
  •   enzo26 · 2023-03-15 10:53:56 +08:00 · 1533 次点击
    这是一个创建于 379 天前的主题,其中的信息可能已经有所发展或是发生改变。

    请教一下,下面的例子明明 drop 了两次,为什么没报错呢,好像第一次没生效一样

    fn test_double_free()
    {
    
        let mut my_vec = Vec::new();
        my_vec.push("Hello");
        let first_elem = my_vec.first().unwrap();
        
        // 尝试在第一次释放后再次释放内存
        drop(first_elem);
        println!("{:?}", first_elem);
        drop(my_vec);
        
    }
    
    7 条回复    2023-03-16 09:59:19 +08:00
    f1ush
        1
    f1ush  
       2023-03-15 11:28:35 +08:00
    以我浅薄的 rust 知识来看,
    1. 这里根本没有发生 double free
    2. 第一次 drop 掉的是 first_elem 的 copy ,不然 println 那里已经报错了
    3. 只有最后一次 drop 才是真的把你的数组释放了
    f1ush
        2
    f1ush  
       2023-03-15 11:29:03 +08:00
    BrettD
        3
    BrettD  
       2023-03-15 11:39:52 +08:00
    first_elem 是一个引用,不是值
    enzo26
        4
    enzo26  
    OP
       2023-03-15 13:26:27 +08:00
    @BrettD drop 参数是引用的话,什么效果呢
    Slurp
        5
    Slurp  
       2023-03-15 14:17:01 +08:00
    这种代码跑 clippy 是不过的:

    error: calls to `std::mem::drop` with a reference instead of an owned value. Dropping a reference does nothing
    --> src/main.rs:8:3
    |
    8 | drop(first_elem);
    | ^^^^^^^^^^^^^^^^
    |
    note: argument has type `&&str`
    --> src/main.rs:8:8
    |
    8 | drop(first_elem);
    | ^^^^^^^^^^
    = help: for further information visit
    = note: `#[deny(clippy::drop_ref)]` on by default

    `Vec` 取元素一般都是返回引用,因此这里是 &&str 。drop 并没有什么用。

    不过就算是 &str ,也是 drop 不掉的。这里的例子换成 String 可能更好理解一点。
    Slurp
        6
    Slurp  
       2023-03-15 14:17:42 +08:00
    enzo26
        7
    enzo26  
    OP
       2023-03-16 09:59:19 +08:00
    @Slurp 谢谢,明白了,确实 drop string 的引用好像也没有效果
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1668 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 16:46 · PVG 00:46 · LAX 09:46 · JFK 12:46
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.