Closed
Description
Miri does not detect any leak for the following code since the reference is stored in a static
variable and is therefore accessible for the whole duration of the program.
use std::sync::Mutex;
static REF: Mutex<Option<&'static i32>> = Mutex::new(None);
pub fn main() {
let a = 123;
let b = Box::new(a);
let r = Box::leak(b);
println!("{r}");
*REF.lock().unwrap() = Some(r);
}
However, replacing the static
with a thread_local!
, Miri complains about a memory leak:
use std::cell::Cell;
// static REF: Mutex<Option<&'static i32>> = Mutex::new(None);
pub fn main() {
let a = 123;
let b = Box::new(a);
let r = Box::leak(b);
println!("{r}");
thread_local! {
static REF: Cell<Option<&'static i32>> = Cell::new(None);
}
REF.with(|cell| {
cell.set(Some(r));
})
}