V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
enzo26
V2EX  ›  Rust

double free 为什么不报错?

  •  
  •   enzo26 · Mar 15, 2023 · 2726 views
    This topic created in 1152 days ago, the information mentioned may be changed or developed.

    请教一下,下面的例子明明 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 replies    2023-03-16 09:59:19 +08:00
    f1ush
        1
    f1ush  
       Mar 15, 2023
    以我浅薄的 rust 知识来看,
    1. 这里根本没有发生 double free
    2. 第一次 drop 掉的是 first_elem 的 copy ,不然 println 那里已经报错了
    3. 只有最后一次 drop 才是真的把你的数组释放了
    f1ush
        2
    f1ush  
       Mar 15, 2023
    BrettD
        3
    BrettD  
       Mar 15, 2023
    first_elem 是一个引用,不是值
    enzo26
        4
    enzo26  
    OP
       Mar 15, 2023
    @BrettD drop 参数是引用的话,什么效果呢
    Slurp
        5
    Slurp  
       Mar 15, 2023
    这种代码跑 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  
       Mar 15, 2023
    enzo26
        7
    enzo26  
    OP
       Mar 16, 2023
    @Slurp 谢谢,明白了,确实 drop string 的引用好像也没有效果
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3151 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 14:37 · PVG 22:37 · LAX 07:37 · JFK 10:37
    ♥ Do have faith in what you're doing.