3 ms·
As lmkg pointed out, leaking memory is considered safe in Rust. There are a number of factors here: - Leaking memory doesn't cause Undefined Behavior. It might
by oconnor663 6y ago
As lmkg pointed out, leaking memory is considered safe in Rust. There are a number of factors here:
- Leaking memory doesn't cause Undefined Behavior. It might eventually cause your program (or your whole machine) to lock up or crash, but there are many types of bugs that can do that.
- Categorically preventing memory leaks is difficult without a garbage collector. The biggest problem is that you can use reference counted smart pointers like Arc<T> to create reference cycles. Preventing you from doing that at the language level would be too constraining for a lot of real world programs. (In practice, those programs need to break cycles manually using "weak" references.)
- The difference between "reachable" and "unreachable" leaks isn't so big in practice. For example, if I'm caching some data in a global HashMap, I might forget to clear that map, or I might not clear it frequently enough. If the map ends up consuming all of my memory, the effect on my program is the same as if I'd just leaked all that memory. Either way, I need to debug what's going on and make a code fix. (In fact, at least some of the leaks that the Actix post is referring to are this sort of reachable leak.)
For all these reasons put together, Rust allows safe code to leak memory. In fact, there's even a safe standard library function for doing it (https://doc.rust-lang.org/std/mem/fn.forget.html https://doc.rust-lang.org/std/mem/fn.forget.html). But it's quite rare to run into unreachable memory leaks in practice, because destructors almost always free memory for you automatically.