Skip to content

Data reachable from thread-local storage of the main thread should not be considered leaked #2881

Closed
@lukechu10

Description

@lukechu10

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));
    })
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-leaksArea: affects the memory leak checkerE-good-first-issueA good way to start contributing, mentoring is available

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions