r/cpp • u/ASA911Ninja • 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.
- Use smart pointers instead of raw pointers
- 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
19
u/KFUP Jan 03 '26
They are not, why do you think they are?
327
u/Infamous-Bed-7535 Jan 03 '26
It is a misconception that c++ developers are spending their time on memory leaks and manual memory management.
Using modern c++ you can easily write secure and performant, dense yet very readable code.
121
u/trad_emark Jan 03 '26
smart pointers alone are insufficient to *guarantee* no memory leaks. specifically, you can create a cyclic references, that would prevent deallocation, even when all outside references into the cycle are removed. to detect such cases a proper garbage collected language is required.
that said, using smart pointers is essentially the next best option.
16
u/ShakaUVM i+++ ++i+i[arr] Jan 03 '26
They're not. Valgrind has been around for ages (getting people to USE it is harder than using it lol), but more recently ASAN has provided basically a zero effort way of finding most memory errors. Just turn the flag on (-fsanitize=address) and off you go.
84
u/AKostur Jan 03 '26
Yup, you're missing legacy code. Stuff that was written by people who didn't bother to use the smart pointers because they're used to malloc/free, so just use the newfangled new/delete and everything will be fine. This may sound pretentious, but I haven't written a memory leak in probably over a decade (at least not in C++).
8
u/SoerenNissen Jan 03 '26 edited Jan 03 '26
Because the code base is 50 million lines and half of them are C code from 1996. (The leaks probably aren't in the C code because that part has 30 years of battle testing but you don't know that when you get them so they're still part of what you're debugging through.)
Real answer: I have never received a ticket as a result of shipping a memory leak and I don't remember ever finding a memory leak in pre-ship testing either, but I have definitely written a bunch of memory leaks in leetcode problems, mainly because the code had to conform to the interfaces leetcode expect and those can be very pointer-heavy, very different to the style I write in when doing stuff outside of leetcode.
10
u/CluelessDoom Jan 03 '26
They are not hard to solve. They are not hard to find.
Finding path of reproduction can be tricky(e.g. can only happen in Release builds or happen only when running long enough, can depend on the data software is working with) - but that is true for all the bugs.
Most of the time good tooling will help you.
The hard part is when you only have coredump and rough description from client. Now that can be hard.
4
u/ivancea Jan 03 '26
It's not hard; you just have to follow some practices and patterns to avoid it. The hard part is finding a leak when it exists already.
To give you another perspective, I work on a Java project that has its own memory tracking to prevent OOMs. Similar to manually allocating memory, but instead we increment or decrement a "used bytes" counter. It works well, we have strict rules to how we handle exceptions at every step, and how we track/release that memory. However, if we forget or don't see a single point of failure that could lead to such a leak, the fun begins. We have lots of tests to detect leaks, and they rarely happen. But race conditions, multithreading... Everything adds to the equation, making things harder.
That said, Java doesn't have RAII, it just has the try-with-resources syntax sugar. In C++ it's easier to do it correctly. But, as commented, the problem begins when you don't. And trust me, it happens. Maybe not in a small app, but add for example dynamic libraries with shared memory of things like that. Things end up... Complicated
4
u/Ty_Rymer Jan 03 '26
they're not difficult to solve, especially with the existence of adress sanitizer. it's really one of the least difficult problems. race conditions on threads and accidental sharing is much more difficult to solve. especially if you need to keep the best performance.
4
u/MRgabbar Jan 03 '26
I have the same shock when I realized that modern C++ barely has any leaks or even memory corruption issues. The first project I examined with next to no issues is Multipass. That is the reason why to me C++ is the ultimate language, the speed and power of C and the quality of life improvements from OOP patterns.
10
u/waffle299 Jan 03 '26
A few years ago, I wrote a highly performant embedded signal analysis library. Despite juggling 2 KHz worth of input in real time, there were no memory leaks. And I verified this with multiple code profilers, optimizers, leak trackers and other systems. (Yeah, it was that kind of project).
I attribute this to fully modern (for the time) C++ with smart pointers, RAII, and extensive use of test driven development.
11
u/kevinossia Jan 03 '26
They’re not hard to solve. Memory management is easy. As a C++ developer for the last 10 years I’ve probably spent 0.01% of my time chasing memory leaks.
Also, you can cause leaks in Java as well, despite what they say. I’ve done it myself. Not hard at all.
Memory management isn’t what makes C++ hard, not even close. It’s all the other stuff.
3
u/ejl103 Jan 03 '26
I'll tell you where I do spend an inordinate amount of time tracking memory leaks and its not C++ - its always managed/GC languages. (Where an unexpectedly retained reference is a "leak" and can keep a lot alive)
3
u/pjf_cpp Valgrind developer Jan 03 '26 edited Jan 05 '26
Memory leaks are not too hard to solve.
However I would also say that many beginners (and even not so beginners) do not have a good understanding of how memory allocation works and what the potential errors are.
If we just limit ourselves to leaks then there are degrees of correctness.
At the first degree you should be asking yourself "will my program run out of memory and crash?". For a small tool that runs for a fraction of a second it doesn't even matter too much if you leak. For long running and/or large applications then you need to start taking care. If you have a severe memory leak then your program will probably exhaust memory in a matter of seconds or minutes. On the plus side, like segfaults, you will probably be able to identify and fix the leak quickly. More insidious are the very slow leaks, particularly in daemons/services that may be running for months or years.
At the second degree you should be asking yourself "is my program making optimum use of memory?". There is no simple answer to that. In order to reduce memory pressure on the system it is usually better to free memory as as soon as it is no longer needed. Freeing memory is somewhat expensive so you may want to use some alternative technique that recycles allocated memory.
There are a couple of tangential issues. "Is my program easy to maintain?", that conflicts somewhat with complex memory recycling. "Can I detect leaks easily?", again using memory pools can make that more difficult. Also if your application has many leaks then it may be hard to see the woods for the trees when it comes to detecting extra leaks.
Finally, there are a few corner cases where it is tricky to ensure that the memory gets freed safely. If you have an object allocated on the heap that is used in error handling (logging, exceptions or whatever) then it is difficult to deallocate that memory. What happens if an error occurs after you have deallocated and you need to handle the exception or log the event? Since these are usually singleton-like allocations you usually just have to put up with these leaks.
7
u/Similar_Sand8367 Jan 03 '26
Think of legacy code which where programmed before smart pointers…
6
u/kitsnet Jan 03 '26
Memory leaks?
You mean, false positives from Valgrind?
The really hard stuff is not memory leaks, but race conditions.
4
u/Rebrado Jan 03 '26
Memory leaks were the nightmare before smart pointers. If you use smart pointers, they don’t happen.
That said, a memory leak is a terrible beast. The compiler does not complain about them. Your code might just work, and never fail, until it does.
2
u/nosyeaj Jan 03 '26
can you give me links for the #2? “Use RAII, Rule of 5/3/0”
2
u/jgaa_from_north Jan 03 '26
Memory leaks are easy to handle in theory. But we often use C libraries from C++, and today many people also use code generated by AI. AI code rarely follow best practices. Yesterday ChatGPT made some code for me to predict the required token-size needed to process a prompt withe the C++ AI library llama.cpp. It refactored the entire prompt function, and removed the call that freed up the memory used. That would be a pretty amazing memory leak if I had not caught it.
Using libraries like openssl directly from C++ is hard, and it's easy to forget or miss a free call. Many of the API functions require a special function to free the memory, and many don't. You have to carefully read the documentation for every function you call.
Another issue that is far worse than memory leaks, is use after free. I often use
std::string_viewandstd::spanin my interfaces in new code, because the consumer of some data, in a particular library or use-case, should not own the data, or even know if know the actual storage type of the data (could be std::string/std::array/std::vector/allocated buffer). The developer who use these interfaces must remember this and make sure that the data exists for the duration of the call into these functions. The functions may be coroutines, or the interfaces could be called by lambdas that are passed to worker-threads. C++ is often used to make very efficient applications, doing many things on all the cores on the machine it runs on in parallel. The more efficient code you write in a complex application, the harder it gets to maintain the life-time of buffers and objects optimally.So yes, in theory it's easy. But it's also easy to get it wrong.
2
u/JVApen Clever is an insult, not a compliment. - T. Winters Jan 03 '26
If you are writing C, you have to read the documentation. Things become tricky when a raw pointer sometimes has ownership. Although, even for those cases you can write your own smart pointer class (and I did).
Though, if you are writing modern C++ (C++14 and above), using std::make_unique solves a lot of problems before they occur. The remaining issues are cycles, bleeding (continuously allocating while correctly reallocating at the end. For example: a push back in a vector of unique_ptr) and threading issues. Though to be fair, these are problematic in every language. I'd rather have a memory leak than a memory bleed, as the leak is obvious where it's going.
The problems start when you are falling back to manual memory management. This is exceptional and usually very contained. Even here, writing simple code and datastructures help a lot.
On top of that, if you are using MSVC, clang++ or g++, you should have the address sanitizer available. Even when you cannot use it, you can use visual leak detector (Windows) or valgrind (Linux, Mac) to get information about the leaks or corruptions.
I know that some people believe legacy code is a problem, though in my experience you can always do small refactorings which modernize the code and solve your issue. It might take more time than just adding a delete in an if-statement, though you have gained that time if you can prevent a second bug like it. (And yes, I have to deal with old C code compiled as C++, and code written in C++98 on a large codebase) If you cannot change your old code, you have bigger problems than memory safety.
2
u/[deleted] Jan 03 '26
No.. its not in general. Things become bit tricky if you want to use raw pointers for what ever reason.
2
u/karlosvas Jan 03 '26
Tengo un amigo llamado Rust que tiene la respuesta a tus preguntas, pero es muy odiado, no me funen tambien me encanta cpp.
2
u/seeking-health Jan 03 '26
It's no longer a problem you can even use raw pointers, Claude Opus can find any memory leak easily even in the most complex codebase
5
u/No_Indication_1238 Jan 03 '26
No. It's just nobody bothers to learn and use smart pointers or RAII, or bounds checking, or checking for null pointers or not remembering that iterators can be invalidated, etc, etc. The memory leaks are trivial to solve after you have read 1 to 2 books explaining C++. The people that have done this aren't online crying about how Rust is so much better, they are making money.
3
u/ZachVorhies Jan 03 '26
No, they rarely happen if you use the right data structures, like shared pointer, and unique pointer
2
u/cdnrt Jan 03 '26
Its no about using the features, its a mental model you will have to learn to get into. Programing is like this abstract tree that trickles down, the more you work on it the more you understand and the better you will get. You need tooling, start looking into profilers, hex viewers etc to give you visuals of whats happening. This does not apply to cpp, this is fundamental, debugging is an acquired skill you gain overtime. Best to learn it now then later.
2
u/Sniffy4 Jan 03 '26
you're glossing over practical situations such as
- cycles of diff objs holding shared_ptr's to each other: neither can be deleted
- obj lifetime mgmt issues: sometimes things get put in a singleton data structure and never get deleted properly for some control-flow reason
2
u/FreitasAlan Jan 03 '26
You have to believe it's a (big) problem, otherwise other people can't sell you a solution. It's the biggest problem all developers have. Trust me.
1
u/wrosecrans graphics and network things Jan 03 '26
Okay, I'll just never do anything that requires dealing with raw pointers like Win32, Posix, or embedded. Oops, I eliminated access to core functionality on pretty much every real world platform.
Obviously, not everything requires that stuff, but some stuff does. You can't just wave an ideological magic wand and make the existing ecosystem go away. For higher level applications, yeah modern stuff without legacy that doesn't need to hook into low level platform stuff is pretty easy to avoid memory problems. And people working at that level mostly do. Your average desktop PC has tons of C++ code, way more than it did in the mid 90's, and yet modern PC's are fairly stable and mostly work fine despite having all that surface area.
1
u/angelajacksn014 Jan 03 '26
In a brand new codebase that starts with proper guidelines? No.
In a 100 kloc codebase that started out with c++11 or god forbid older? It can be lol
1
u/perspectiveiskey Jan 03 '26
Memory leaks were a common thing 20 years ago when you still routinely did
char* lpszHostName = new char[32];.Today, writing that line in any codebase would be seen as a sign that you're not a good developer. There's really never a good reason to do it like that.
These days, where memory leaks occur is when you make use of some legacy but ultra battle hardened piece of code that is deployed on 200 million devices, but is written in C. It's easy to not correctly wrap the interface and get in tricky edge conditions.
I can think of many such libraries: gzip, openssl, socketcan...
1
u/LegendaryMauricius Jan 03 '26
No, but if you're not structuring your code from the start to keep track of ownership it's hard to remember not to cause them. And if you do, then it's hard to solve them (without valgrind of course).
1
u/bert8128 Jan 03 '26
One problem you may well come across is that the code you are working on has been continuously developed over the last 30 years and there are a lot of raw pointers in there. And if there are a couple million lines of it, and it pretty much works, a re-write is hard to justify.
1
u/SmokeMuch7356 Jan 03 '26 edited Jan 04 '26
Use standard containers where possible. Where not possible, use smart pointers and follow RAII principles.
And even then there are no guarantees.
I work on a service that uses a
std::mapto keep track of requests while we're processing them, the idea being we'd remove them when we're done.Except in one set of circumstances requests weren't being removed and the map was growing without bound. It took a while before we caught it because the service gets kicked every eight hours to renew credentials, but recently traffic on that service went up a couple of orders of magnitude and we started running out of memory.
This was a stupid application-level error, but it shows how memory leaks can show up even when you're using standard containers.
It's not just the tools, it's how you use them.
1
u/max_remzed Jan 03 '26
yes
1
u/Light_x_Truth Jan 03 '26
That if is not true generally.
1
u/snarkhunter Jan 03 '26
The memory leaks that aren't solved by following those are the hardest ones to solve
1
u/Casalvieri3 Jan 03 '26
There are two problems here:
1.) Lots and lots of legacy C++ that doesn’t use smart pointers.
2.) Enforcement of good coding practices is down to managers—who always want code completed and we can worry about safety later. If a non-smart pointer (dumb pointer?) is passed it’s likely down to programmer discipline as to safely freeing pointers.
1
u/mkrevuelta Jan 03 '26
Millions of lines of code retorted by hundreds of hands without smart pointers, git, proper tests or even proper specifications during twenty years. Rewriting from scratch is completely out of question. And there's a lot of that driving the world.
That is hard to solve.
1
u/keyboard_toucher Jan 03 '26
Those "rules" do not suffice to avoid memory leaks. I suppose there are no general and easy-to-follow rules that guarantee absence of memory leaks. However, I would not say that memory leaks are particularly difficult or time-consuming problems when they occur. Address Sanitizer, as some others have mentioned, is helpful for tracking them down.
1
u/heliruna Jan 03 '26
There are several reasons that make memory leaks a problem:
There is still a lot of legacy code around that has memory leaks due to manual memory management. Modern code using RAII in large projects will be used in addition to manual memory management, it does not replace the old code completely.
Combining code that has no memory leaks but uses reference counting does not necessarily compose to code without memory leaks. Your app has no memory leaks, your plugin has no memory leaks, my plugin has no memory leaks, but if anyone uses your app with your plugin and my plugin, a cyclical reference will be formed and there is a memory leak.
Memory leaks tend to be sneaky. If I am a software developer rebuilding my application every couple minutes I may never notice a memory leak that only happens after a couple hours.
We have reliable tooling to detect memory leaks (valgrind, ASan, heaptrack), that is still not used everywhere. There are also resource leaks not covered by those tools (e.g. GPU allocations). But most importantly, there is no tooling that tells you where you forgot to release the memory. They all tell you at application exit that there were memory leaks, but it may take weeks of manual investigation to find the root cause. Most businesses decide to restart the software every 24h instead.
1
u/dobkeratops Jan 04 '26
mr carmack says "if it's syntactically legal.. it will appear in the codebase"
C++ has it's C-like subset and legacy "C with classes" and it's hard to tell at a glance if the rules of modern C++ are being followed or not. C++ is important precisely because of the huge amount of legacy code that goes all the way back to C projects that got gradually upgraded, and closer interfacing with C than any other language.
and you also bring up the point that concurrency makes it harder.. and we're something like 2 decades into the world of consumer devices being multicore .. concurrency & parallelism is the default if you want to make full use of a modern processor
1
u/NilacTheGrim Jan 04 '26
They are hard to solve because generally the programming practices that lead to them indicate such bad design that likely everything needs to change to truly solve them.
If you follow the proper practices you should have no leaks, ever.
1
u/Eweer Jan 04 '26
If you and I use actual C++, then memory leaks should be extremely rare to happen. The issue is those monstrosities of code bases out there that are staying together with hay and (a lot of) duck tape from 20 years ago when memory leaks were a second thought.
1
u/AssemblerGuy Jan 05 '26
Because they usually appear in messy code, where ownership is unclear and developers disregarded established guidelines.
1
u/gdvs Jan 05 '26
You can get memory leaks in any programming language. Keeping a reference by accident suffices. It's a bug and people don't usually write bugs on purpose. And sometimes it's not obvious why it happens.
1
u/DownhillOneWheeler Jan 06 '26
It isn't hard. It used to be more difficult, but not beyond a reasonably competent and diligent developer.
C++ inherited manual resource management from C. RAII was possible but a lot of people seem not to have understood it or relied on it. I've always found this baffling. Smart pointers were possible but did not exist in the standard library until the now defunct std;;auto_ptr (a partial solution at best). So... we had a very long period of basically terrible resource management thanks to C-style development practices. C++ has many faults, but I feel it has been unfairly (or at least avoidably) maligned in this regard.
1
u/guywithknife Jan 06 '26
I mainly use C++ for hobbyists game engine development and I largely don’t think about memory leaks and consider it a solved problem. My approach is:
Use arenas and pools with well defined lifetimes (eg per frame bump allocator), use well defined ownership (I know what systems own what) and lifetimes (I know when a system or object is created, used, and destroyed), use RAII (when I need to access something, I can guarantee it gets released when I’m done).
Interacting with third party libraries does mean there’s some manual management, but it’s mostly wrapped in the above and kept manageable that way.
1
u/Raknarg Jan 06 '26
They can be hard to solve, and they can be subtle, like a leak happening from invoking a constructor/destructor, or something not being handled properly in a destructor, or maybe there's some multithreading going on, all kinds of reasons leaks can happen. Theyre inherently difficult to trace cause its not usually some overt problem, of "this logic here doesn't work", its that somewhere along the way something lost track of some item and we need to figure out why that would happen. And also without some advanced tools that I'm not familiar with, I'm not sure how much insight you can even have into the data. My experience with memory leak tools is just using valgrind, and in the past the only context I was using was the size of the leak and the size of the blocks to determine what thing could even be leaking it. Your program doesn't inherently know anything about the leaked data other than what the values are and how big it is.
We have a lot of practices and tools now that avoid leaks, which is good. But when leaks happen, they can be hard to find.
1
u/adamf88 Jan 07 '26
It is controversial if it is a real leak or not. But imagine that you have vector<int> and add just a few of bytes every second to this vector. And you forgot to clear it at all (leak).
In application with millions lines of codes and tones of random allocations (small & big). It is very difficult to spot this particular one.
For very long time resizes of this vector are small enough so they are hidden in the mess of other allocations.
Memleak detector tools don't see it, because if you close the app then destructor releases memory (so it is "clean").
On the other hand if you keep running the app on production then after e.g. year it will consume enough memory to crash your system.
1
u/zl0bster Jan 09 '26
It is not just memory leaks.
Resize vector. Ups, you invalidated iterators/pointers.
Use string_view and pointed to stuff gets deallocated. Ups.
You added not pod member to struct that is getting memcopied. Ups.
1
u/Various_Bed_849 Jan 03 '26
This is a fun thread. It’s like reading about those experiments where people rate their own driving and 80% think they drive better than average.
Valgrind and sanitizers are all great, but they only cover the code paths exercised during testing. Few use these tools to any extent outside of their test environments. Even with code coverage of 100% you typically cover less than half the code paths exercised in production. I would guess much less.
I myself have been part of a small group of people who fixed bugs in a code base with millions of lines of code where the stack traces where corrupted due to memory overwrites. This with a user base of several hundreds of millions. Frustrating but fun and none of the developers causing the bugs fixed these themselves.
Here is an interesting read of memory related issues that ended up in production: https://security.googleblog.com/2024/09/eliminating-memory-safety-vulnerabilities-Android.html?m=1
I’d say a fair answer is that with proper tooling and guidelines you catch the vast majority of these bugs. The rest can cause you severe headaches. Especially in combinations with race conditions.
1
u/WorkingReference1127 Jan 03 '26
Potentially contentious, but when you see people complaining aboput C++ being so "memory unsafe" remember two things:
malloc().Put two and two together and you get this awkward divide between people who use modern tools and rarely have memory problems and people who do the exact opposite being put together under one banner.
Not saying it's impossible for modern C++ users to create memory issues or that it doesn't happen; but just something to bear in mind.
1
u/mredding Jan 03 '26
Herb Sutter recently points out that surveyors are biased - they conflate C with C++ in their reports, skewing the results. He showed that if you can find an analysis of languages that separate C and C++, then you'll find that C++ seems to be more memory safe than even Python, and that almost half of all memory leaks alone are caused by C code.
C++ has basically solved memory problems, and our industry has been saying it for over a decade now. And it's hardly anything to do with the language itself - most of the work is just in the standard library. Smart pointers have been around a long time - pre-standard, Boost introduced a smart pointer library in 2000, but in C++11, they were incorporated into the standard library, making it inexcusable to NOT use them.
You can write bad code in C++, we have most of the C standard library available to us, but the question is how easy is it to write correct code? How efficient? How effective? We have a standard string type that's fairly robust and easy to use, there's no reason not to. In C, you don't have a standard string type, just character pointers and some dodgy methods that are inconsistent - with behaviors you have to be aware of. This leads you to having to write your own string type - which few bother, or use a string library, which are a dime-a-dozen - and if we couldn't get people pre-C++11 to adopt 3rd party smart pointers, what hope do we have of getting C developers to be more consistent about using a 3rd party string library? It hasn't happened yet. It ain't happening now.
C++ makes it easy to write correct code. C merely makes it possible.
1
u/sessamekesh Jan 03 '26 edited Jan 03 '26
"Memory leaks" is a pretty broad category, and I think it's worth addressing as such.
Use-after-free and dangling references are easy enough to solve if you're using RAII and C++11 smart pointers. You can "solve" those with modern code, yes. So long as you're being diligent to use those tools correctly you will not have those types of memory leak in your code, but that safety goes away with methods that return underlying unsafe references like
shared_ptr.get()orsome_vector.data().Circular references are still very possible and very capable of leaking memory - a contrived example:
I've run into that category of memory leak in several languages, even garbage collection + statically enforced lifetime semantics won't safe you from those.
There's also the good ol' classic "I use more memory than I need" flavor of memory leak - e.g., setting up a buffer to cache requests that you never limit or flush, so it just munches up 8GB in nonsense that's not needed.
EDIT: But yes, for the most part the naive (and common, and annoying) category of memory leaks is more or less solved since the 2011 version of C++. A lot of us are still mucking around in code from well before 2011 and interfacing directly with C which doesn't have those features, so you'll find C++ devs who both do and don't have to face memory concerns very often.
1
u/CocktailPerson Jan 03 '26
Memory leaks are the easiest memory error to prevent. But that doesn't mean your rules prevent all memory errors. Use-after-frees caused by iterator invalidation are far more common and far more pernicious. It's one thing to say "don't use raw pointers," but iterators are effectively no safer than raw pointers, and using them is absolutely unavoidable.
0
u/cdcformatc Jan 03 '26
it's difficult to know you even have a memory leak in the first place. finding it is also difficult. fixing it is easy.