r/cpp • • Jan 03 '26

Are memory leaks that hard to solve?

I have been coding in cpp for the last year (not regularly) and don’t have any professional experience. Why are memory leaks so hard to solve? If we use some basic rules and practices we can avoid them completely. 1) Use smart pointers instead of raw pointers 2) Use RAII, Rule of 5/3/0

I might be missing something but I believe that these rules shouldn’t cause memory related issues (not talking about concurrency issues and data races)

97 Upvotes

230 comments sorted by

View all comments

Show parent comment

-3

u/ASA911Ninja Jan 03 '26

Ig my opinion stems from the fact that everyone is talking abt rust. There are some examples like why google made go(gc), why rust was made by Mozilla, microsoft shifting to rust etc

17

u/CocktailPerson Jan 03 '26

Yeah memory leaks aren't why Rust and garbage-collected languages exist. Use-after-frees are the main aspect of (temporal) memory safety that Rust has solved and C++ can't.

2

u/QuaternionsRoll Jan 03 '26

Also uninitialized memory, thanks to the semantics of default initialization carrying over from C.

14

u/the_poope Jan 03 '26

You can also have cyclic references and thus memory leaks in Rust. But memory leaks aren't a security issue, it just causes the program to crash when you run out of memory.

5

u/mcfish Jan 03 '26

I'd dispute that last statement. It's likely platform dependent but if a system is out of memory, the OS may start killing processes. It might kill the leaking app, or some other process, since it probably has no way of knowing whether the growth in memory usage of your app is a leak or legitimate.

Similarly, I'd imagine on other OSes, your app hogging too much RAM could cause other processes to crash, or just not work properly, when they try and fail to allocate. So essentially a leaking application can cause denial of service to other services, which I would call a security issue.

-1

u/QuaternionsRoll Jan 03 '26

Memory leaks are generally not considered a memory safety issue because they cannot result in undefined behavior. You can exploit leaks to initiate a DoS attack, sure, but not much else.

2

u/meyriley04 Jan 03 '26

I mean it can be a security issue if the attacker intentionally exploits a memory leak crash to take down a specific system, no? Or just DoS

27

u/[deleted] Jan 03 '26

rust's main goal is not preventing memory leaks. And it is also not why people use it

18

u/Farados55 Jan 03 '26

Rust’s main advantage is memory safety.

9

u/[deleted] Jan 03 '26

it's actually safe to leak memory in rust

https://doc.rust-lang.org/std/vec/struct.Vec.html#method.leak

2

u/MEaster Jan 03 '26

Both Rust and C++ handle memory leaks the exact same way: smart pointers and RAII. I think both languages handle that issue about as well as you can without a garbage collector.

0

u/[deleted] Jan 03 '26

Rust has smart pointers, but the majority of handling memory is not used using smart pointers.