pretzelhammer / rust-blog

Educational blog posts for Rust beginners
Apache License 2.0
7.53k stars 396 forks source link

Update common-rust-lifetime-misconceptions.md #73

Closed mindeng closed 8 months ago

mindeng commented 10 months ago

It's possible to get a 'static reference to dynamically allocated data at run-time via a memory leak, but without the cost of leaking memory, because:

  1. We can restore the Box back from the reference, by using Box::from_raw.
  2. The Box will then take care of freeing the memory (after it is dropped).

Here is an example to demonstrate this process:

use rand;

#[derive(Debug)]
struct A {
    s: String,
}

impl Drop for A {
    fn drop(&mut self) {
        println!("{:?} has been dropped!", self);
    }
}

fn leak_a() -> &'static A {
    let rand_string = rand::random::<u64>().to_string();
    let a = A {
        s: rand_string,
    };
    Box::leak(a.into())
}

fn main() {
    let a = leak_a();
    println!("a = {:?}", a);

    // restore `a` Box from the leaked reference
    let a = unsafe {
        let const_ptr = a as *const A;
        let mut_ptr = const_ptr as *mut A;
        Box::from_raw(mut_ptr)
    };
    println!("a = {:?}", a);

    // `a` will be dropped here
}

Output:

a = A { s: "14376733450705693403" }
a = A { s: "14376733450705693403" }
A { s: "14376733450705693403" } has been dropped!