Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to cause a memory leak in 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?

like image 516
Newbyte Avatar asked Apr 06 '19 20:04

Newbyte


2 Answers

Yes, leaking memory in Rust is as easy as calling the std::mem::forget function.

You can also leak memory if you create a cycle of shared references:

A cycle between Rc pointers will never be deallocated. For this reason, Weak is used to break cycles. For example, a tree could have strong Rc pointers from parent nodes to children, and Weak pointers from children back to their parents.

You can also use Box::leak to create a static reference, or Box::into_raw in an FFI situation.


Actually, in a system programming language, you need to be able to create a memory leak, otherwise, for example in an FFI case, your resource would be freed after being sent for use in another language.


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 a very specific thing.

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.

like image 126
Boiethios Avatar answered Oct 19 '22 04:10

Boiethios


From the 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.

So the answer is yes. You can have memory leaks in your code and rust compiler won't complain about it.

like image 18
theJian Avatar answered Oct 19 '22 04:10

theJian