Search code examples
pointersmemory-leaksrust

Why does Rust consider it safe to leak memory?


According to this chapter in the Rust Book, it is possible to leak memory by creating a cycle of pointers:

Rust’s memory safety guarantees make it difficult, but not impossible, to accidentally create memory that is never cleaned up (known as a memory leak). Preventing memory leaks entirely is not one of Rust’s guarantees in the same way that disallowing data races at compile time is, meaning memory leaks are memory safe in Rust. We can see that Rust allows memory leaks by using Rc<T> and RefCell<T>: it’s possible to create references where items refer to each other in a cycle. This creates memory leaks because the reference count of each item in the cycle will never reach 0, and the values will never be dropped.

There exist alternatives like "weak pointers" that would allow you to create self-referential structures that could still be cleaned up when dropped. In fact, using Weak<T> is actually suggested later in that chapter.

Why does Rust consider this safe? Why is this an instance where the language does not do anything to prevent 'bad programmer behaviour'?


Solution

  • Because it is safe.


    unsafe has a very specific meaning in Rust, it specifically targets classes of programming mistakes which trigger Undefined Behavior. Those are the nastiest mistakes, as they completely subvert your whole understanding of a program, allowing either compiler or hardware to behave in unpredictable ways.

    Memory leaks do not trigger Undefined Behavior, and therefore are safe.

    You may be interested in what the Nomicon (the Unsafe equivalent of the Rust Book) has to say about Leaking; the example about ScopeGuard is often referred to as the Leakpocalypse.


    It is notable that Garbage Collected languages can easily leak memory, for example. A simple Map in which key-value pairs are added without ever being removed will eventually lead to heap exhaustion; and the GC will not be able to stop it.

    An ever-growing Map is as undesirable as repeatedly forgetting to free a pointer, in either case heap exhaustion looms, yet GC'ed languages are considered safe in general.