Why does Rust consider it safe to leak memory?

£可爱£侵袭症+ 提交于 2020-01-02 04:54:07

问题


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'?


回答1:


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.



来源:https://stackoverflow.com/questions/56107324/why-does-rust-consider-it-safe-to-leak-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!