Realistically, most supposed "C++ codebases" in which these errors happen are C codebases in disguise. Some good old pointer arithmetic overwriting the far more useful stack.
Because even with new/delete, you probably have those pairs sit either in constructors/destructors, or well-reviewed parts of the code with error handling, or rely on simple patterns like delete-if-not-null (which is exactly what unique_ptr does).
Agreed, I see more overuse of std::shared_ptr these days. End up with circular dependencies, lifetime issues, and extra atomic ops due to not using std::unique_ptr or std::weak_ptr correctly.
Memory leaks are explicitly considered “safe” it is why Refrence Count pointers are allowed in safe rust, it’s easy to create a cyclical chain with them that will never get dropped.
Memory leak aren't memory unsafe though. It's not gonna cause a bad dereference or data corruption, it's just your program forgot that data existed and moves on.
An annoyance and a resource use issue, sure, but not unsafe.
Shared pointers work by counting the number of things that are referencing the object in memory through a pointer and only free the memory on destruction of the shared pointer when the reference count equals zero.
Scenario: Consider the case where objects A, B, and C exist and are all dynamically allocated. B and C point to each other with a shared pointer and A points to B with a shared pointer. In this scenario assume the only way to reach C is through B and therefore through A. B has a reference count of 2 (A and C both point to it) and C has a reference count of 1 (B points to it) and A has a reference count of 1 (whatever is points to A in this scenario). Let’s say A’s reference count goes to zero and therefore A is deleted. B’s reference count drops to 1 (A no longer points to it, but C still does) and C still has a reference count of 1 (B still exists so it still points to it). You have now leaked the memory of B and C since their reference counts will never reach 0 and there is no way to access them anymore.
There are other similar “circular reference” memory leaks that can happen.
140
u/pflasti Sep 06 '26
I had my last memory bug before the team agreed on a strict "no new/delete" policy. That was years ago
375
u/JackNotOLantern Sep 06 '26
All c++ memory problems are a skill issue. Rewriting in rust is admitting weakness.
56
u/Any_Obligation1652 Sep 06 '26
Use containers and smart pointers a voila no memory leaks
12
u/ducon__lajoie Sep 06 '26
Unrelated, but who the fuck installed this ugly ass stone veneer around the window? That's a worse offense than using goto in c++.
3
u/Stjerneklar Sep 07 '26
<guten> </guten>
6
u/Sentouki- Sep 06 '26
Rust, the "I use arch btw"-type of language
1
u/yuehuang Sep 07 '26
Performance is a memory bug by definition.
-3
u/One_Garlic_4938 Sep 06 '26
the berlin wall had a similar average down time