How do I free memory in a lazy_static?

1.2k Views Asked by At

The documentation states that if the type has a destructor, it won't be called: https://docs.rs/lazy_static/1.4.0/lazy_static/#semantics

So how am I supposed to free the memory?

2

There are 2 best solutions below

0
On BEST ANSWER

So how am I supposed to free the memory?

Make your lazy_static an Option, and call take() to free the memory once you no longer need it. For example:

lazy_static! {
    static ref LARGE: Mutex<Option<String>> =
        Mutex::new(Some(iter::repeat('x').take(1_000_000).collect()));
}

fn main() {
    println!("using the string: {}", LARGE.lock().as_ref().unwrap().len());
    LARGE.lock().take();
    println!("string freed")
    assert!(LARGE.lock().is_none());
}

Playground

As others have pointed out, it is not necessary to do this kind of thing in most cases, as the point of most global variables is to last until the end of the program, at which case the memory will be reclaimed by the OS even if the destructor never runs.

The above can be useful if the global variable is associated with resources which you no longer need past a certain point in the program.

4
On

So how am I supposed to free the memory?

That question isn't even wrong.

The entire point of lazy_static is that the object lives forever, that's what a static is, when would anything be freed? The note is there for non-memory Drop, to indicate that if e.g. you use lazy_static for a file or a temp they will not be flushed / deleted / … on program exit.

For memory stuff it'll be reclaimed by the system when the program exits, like all memory.