根据 this chapter in the Rust Book ,可以通过创建指针循环来泄漏内存:
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>
andRefCell<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.
存在诸如“弱指针”之类的替代方法,可以让您创建自引用结构,这些结构在删除时仍然可以被清除。事实上,使用 Weak<T>
实际上是在该章的后面建议的。
为什么 Rust 认为这是安全的?为什么这是一个语言不采取任何措施来防止“不良程序员行为”的实例?
最佳答案
因为安全。
unsafe
在 Rust 中有非常具体的含义,它专门针对触发 Undefined Behavior 的编程错误类。这些是最严重的错误,因为它们完全颠覆了您对程序的整体理解,使编译器或硬件以不可预测的方式运行。
内存泄漏不会触发未定义的行为,因此是安全的。
您可能对 Nomicon(相当于 Rust Book 的 Unsafe)关于 Leaking 的内容感兴趣;关于 ScopeGuard
的示例通常被称为 Leakpocalypse。
值得注意的是,例如,垃圾收集语言很容易泄漏内存。一个简单的 Map
,其中添加了键值对,但从未被删除,最终会导致堆耗尽; GC 将无法阻止它。
不断增长的 Map
与反复忘记 free
指针一样令人不快,在这两种情况下都会出现堆耗尽,但 GC 处理的语言通常被认为是安全的.
关于pointers - 为什么 Rust 认为泄漏内存是安全的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56107324/