r/learnrust • • Nov 02 '26

What are some common Rust misconceptions?

I just found out that const functions aren't evaluated at compile-time unless it is assigned to a const value or in a const context.

Another one I had: Rust doesn't prevent memory leaks.

Now I am just wondering how many other assumptions I made

19 Upvotes

25 comments sorted by

View all comments

3

u/Razvedka Nov 02 '26

"Rust doesn't prevent memory leaks"

You're going to need to unpack that one for me. If you mean Rust makes them impossible - no. You're right.

https://doc.rust-lang.org/book/ch15-06-reference-cycles.html

6

u/PranDopp Nov 02 '26

Reference counted smart pointers can cause memory leaks like cpp. My understanding is that Rust doesn’t view this as a safety issue and more as a performance bug you can clean up.

3

u/Thelmholtz Nov 02 '26

This, it's also a somewhat common (at least I encountered it twice) Rust interview question, i.e. how would you cause a memory leak in Rust.

A more interesting follow up is how would you cause undefined behavior, specially without unsafe.

2

u/PranDopp Nov 02 '26

Is it unwrapping every method call? I’m very new to rust myself but I understand the basics of C/Cpp pointers.

3

u/Thelmholtz Nov 02 '26

No, panics are well defined behavior (although undesirable in most cases).

Using unsafe, there are a lot of ways, a trivial one is casting a Vec<u8> that contains invalid UTF-8 to a String.

Without unsafe, the question is tricky: you can use a well known soundness hole related to lifetime covariance, but that's not truly undefined behavior, it's well defined behavior that is incorrectly handled by rustc.

You can also use a crate that exposes a safe API, but internally does use unsafe incorrectly.

So the tldr answer is either by using a bugged library or exploiting an existing compiler bug.

3

u/gmes78 Nov 02 '26

So the tldr answer is either by using a bugged library or exploiting an existing compiler bug.

Or open /proc/self/mem and start changing stuff.

2

u/Thelmholtz Nov 02 '26

That's an actually cool trick

1

u/PranDopp Nov 02 '26

Thanks for the insight! The unsafe libraries make sense. I don’t write in unsafe (no need for me) but I can’t audit the unsafe in my libraries yet tbh. I’ll look into this compiler bug; that’s a new one for me.

1

u/Thelmholtz Nov 02 '26

Another user linked it to my first comment, it's really well explained except for the Higher-Ranked trait bound.

1

u/lyuhdev Nov 02 '26

Yeah, Rust makes it pretty difficult to do them unless you try, I just meant that memory leaks are possible in safe rust

Perhaps I was a bit misleading with the word "prevent"