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:
We can restore the Box back from the reference, by using Box::from_raw.
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!
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:Box
back from the reference, by usingBox::from_raw
.Here is an example to demonstrate this process:
Output: