Is this supposed to leak memory?

Suppose I have something like:

struct Foo;

impl Foo {
    pub fn new() -> &'static mut Foo {
        Box::leak(Box::new(Foo {}))
    }
}

then I have another function in my impl like something like:

pub async fn start_processing_thread(&'static self) -> Result<(), Box<dyn std::error::Error>> {
    let listener = tokio::netTcpListener::bind(get_bind_addr(8080)).await?
    loop {
        let (stream, client_socket_addr) = listener.accept().await?;
        tokio::spawn(async move {
            self.handle_request(Box::new(stream))
       });
    }
}

Is there anything wrong with doing this memory wise? Will every new connection cause an increase in memory since it's using self which is a leaked box?

Every time you call Foo::new() you'll leak memory. If you only call it once in your program and then use the leaked instance for every connection, that won't cause you to keep leaking more memory.

1 Like

thats what I figured, ok thanks

A common approach to more explicitly only "leak" memory a single time would be to put the Foo into a static variable instead of a leaked box. (Of course, that wouldn't give you any mut access. But if the &'static lifetime is only needed for immutable reference, you could do the required mutation during initialization.) If constness is a problem, then the types from the once_cell crate could help. I say "leak" since static variables are actually alive for the entire program duration and never destructed, so it's similar to (a limited amount of) leaking.

If the duration the value is kept alive is limited and you don't want leakage, a way to tolfe the 'static requirements from tokio::spawn without leaking is to use an Arc<Foo> instead.

Of course there might be reasons against either of these approaches, I'm just listing them in case you weren't aware.

&'static self is almost always an error, and the right solution is to use self: Arc<Self> instead.

'static anything in Rust is an edge case (it's either for compile-time constants or actual memory leaks). The 'static bounds are not actually a suggestion to ever use 'static references, but they exist to forbid all temporary references. This method of forbidding references leaks to error messages and gives misleading suggestions.

If you see 'static, think Arc.

7 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.