是否有可能在Rust中引起内存泄漏?
有什么方法可以在Rust中引起内存泄漏吗?我知道即使在JavaScript之类的垃圾收集语言中,也有一些极端情况会导致内存泄漏,Rust中有这种情况吗?
Is there any way of causing a memory leak in Rust? I know that even in garbage-collected languages like JavaScript there are edge-cases where memory will be leaked, are there any such cases in Rust?
Yes, leaking memory in Rust is as easy as calling the std::mem::forget
function.
如果您创建一个共享引用的循环,您也可能泄漏内存. >:
Rc
指针之间的循环永远不会被释放.因此,Weak
用于中断循环.例如,一棵树可以具有从父节点到子节点的强Rc
指针,以及从子节点到其父节点的Weak
指针.
A cycle between
Rc
pointers will never be deallocated. For this reason,Weak
is used to break cycles. For example, a tree could have strongRc
pointers from parent nodes to children, andWeak
pointers from children back to their parents.
您还可以使用 Box::leak
创建静态引用,或 Box::into_raw
在FFI情况下.
You can also use Box::leak
to create a static reference, or Box::into_raw
in a FFI situation.
所有这些示例表明,内存泄漏不会破坏Rust所保证的内存安全性.但是,可以肯定地认为,在Rust中,除非执行了非常奇异的"操作,否则没有任何内存泄漏.
All those examples show that a memory leak does not offend the memory safety guaranteed by Rust. However, it is safe to assume that in Rust, you do not have any memory leak, unless you do something quite "exotic".
另外,请注意,如果您对内存泄漏采用了宽松的定义,则有无数种方法来创建内存泄漏,例如,通过在容器中添加一些数据而不释放未使用的数据.
Also, note that if you adopt a loose definition of the memory leak, there are infinite ways to create one, for example, by adding some data in a container without releasing the unused one.