<p>In unmanaged C/C++ code, what are the best practices to detect memory leaks? And coding guidelines to avoid? (As if it's that simple ;)</p>

<p>We have used a bit of a silly way in the past: having a counter increment for every memory allocation call and decrement while freeing. At the end of the program, the counter value should be zero.</p>

<p>I know this is not a great way and there are a few catches. (For instance, if you are freeing memory which was allocated by a platform API call, your allocation count will not exactly match your freeing count. Of course, then we incremented the counter when calling API calls that allocated memory.)</p>

<p>I am expecting your experiences, suggestions and maybe some references to tools which simplify this.</p>

[{'answer_id': 45633, 'author': 'Iain Holder', 'author_id': 1122, 'author_profile': 'https://Stackoverflow.com/users/1122', 'pm_score': 2, 'selected': False, 'text': '<p>Never used it myself, but my C friends tell me <a href="http://en.wikipedia.org/wiki/IBM_Rational_Purify" rel="nofollow noreferrer">Purify</a>.</p>\n'}, {'answer_id': 45635, 'author': 'Paul Tomblin', 'author_id': 3333, 'author_profile': 'https://Stackoverflow.com/users/3333', 'pm_score': 2, 'selected': False, 'text': '<p>There are various replacement "malloc" libraries out there that will allow you to call a function at the end and it will tell you about all the unfreed memory, and in many cases, who malloced (or new\'ed) it in the first place.</p>\n'}, {'answer_id': 45636, 'author': 'Jordi Bunster', 'author_id': 4272, 'author_profile': 'https://Stackoverflow.com/users/4272', 'pm_score': 6, 'selected': False, 'text': '<p>If your C/C++ code is portable to *nix, few things are better than <a href="http://valgrind.org/info/about.html" rel="noreferrer">Valgrind</a>.</p>\n'}, {'answer_id': 45637, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 1, 'selected': False, 'text': '<p>Working on Motorola cell phones operating system, we hijacked memory allocation library to observe all memory allocations. It helped to find a lot of problems with memory allocations. \nSince prevention is better then curing, I would recommend to use static analysis tool like <a href="http://www.klocwork.com/products/insight.asp" rel="nofollow noreferrer">Klockwork</a> or <a href="http://www.gimpel.com" rel="nofollow noreferrer">PC-Lint</a></p>\n'}, {'answer_id': 45639, 'author': 'Rob Wells', 'author_id': 2974, 'author_profile': 'https://Stackoverflow.com/users/2974', 'pm_score': 2, 'selected': False, 'text': "<p>Are you counting the allocs and frees by interpolating your own syscall functions which record the calls and then pass the call to the real function?</p>\n\n<p>This is the only way you can keep track of calls originating from code that you  haven't written.</p>\n\n<p>Have a look at the man page for ld.so. Or ld.so.1 on some systems.</p>\n\n<p>Also do Google LD_PRELOAD and you'll find some interesting articles explaining the technique over on www.itworld.com.</p>\n"}, {'answer_id': 45645, 'author': 'Huppie', 'author_id': 1830, 'author_profile': 'https://Stackoverflow.com/users/1830', 'pm_score': 5, 'selected': False, 'text': '<p>As a C++ Developer here\'s some simply guidelines:</p>\n\n<ol>\n<li>Use pointers only when absolutely necessary</li>\n<li>If you need a pointer, doublecheck if a <a href="http://ootips.org/yonat/4dev/smart-pointers.html" rel="noreferrer">SmartPointer</a> is a possibility</li>\n<li>Use the GRASP <a href="http://en.wikipedia.org/wiki/GRASP_(Object_Oriented_Design)#Creator" rel="noreferrer">Creator</a> pattern.</li>\n</ol>\n\n<p>As for the detection of memory leaks personally I\'ve always used <a href="http://www.codeproject.com/KB/applications/visualleakdetector.aspx" rel="noreferrer">Visual Leak Detector</a> and find it to be very useful.</p>\n'}, {'answer_id': 45652, 'author': 'Serge', 'author_id': 1007, 'author_profile': 'https://Stackoverflow.com/users/1007', 'pm_score': 3, 'selected': False, 'text': "<p>Microsoft VC++ in debug mode shows memory leaks, although it doesn't show where your leaks are.</p>\n\n<p>If you are using C++ you can always avoid using new explicitly: you have <code>vector</code>, <code>string</code>, <code>auto_ptr</code> (pre C++11; replaced by <code>unique_ptr</code> in C++11), <code>unique_ptr</code> (C++11) and <code>shared_ptr</code> (C++11) in your arsenal.</p>\n\n<p>When new is unavoidable, try to hide it in a constructor (and hide delete in a destructor); the same works for 3rd party APIs.</p>\n"}, {'answer_id': 45709, 'author': 'Herms', 'author_id': 1409, 'author_profile': 'https://Stackoverflow.com/users/1409', 'pm_score': 2, 'selected': False, 'text': '<p>If you\'re using Visual Studio it might be worth looking at <a href="http://www.compuware.com/products/devpartner/visualc.htm" rel="nofollow noreferrer">Bounds Checker</a>.  It\'s not free, but it\'s been incredibly helpful in finding leaks in my code.  It doesn\'t just do memory leaks either, but also GDI resource leaks, WinAPI usage errors, and other stuff.  It\'ll even show you where the leaked memory was initialized, making it much easier to track down the leak.</p>\n'}, {'answer_id': 45717, 'author': 'John Sibly', 'author_id': 1078, 'author_profile': 'https://Stackoverflow.com/users/1078', 'pm_score': 2, 'selected': False, 'text': '<p>If you\'re using MS VC++, I can highly recommend this free tool from the codeproject:\n<a href="http://www.codeproject.com/KB/applications/leakfinder.aspx" rel="nofollow noreferrer">leakfinder</a> by Jochen Kalmbach.</p>\n\n<p>You simply add the class to your project, and call</p>\n\n<pre><code>InitAllocCheck(ACOutput_XML)\nDeInitAllocCheck()\n</code></pre>\n\n<p>before and after the code you want to check for leaks.</p>\n\n<p>Once you\'ve build and run the code, Jochen provides a neat GUI tool where you can load the resulting .xmlleaks file, and navigate through the call stack where each leak was generated to hunt down the offending line of code. </p>\n\n<p>Rational\'s (now owned by IBM) PurifyPlus illustrates leaks in a similar fashion, but I find the leakfinder tool actually easier to use, with the bonus of it not costing several thousand dollars!</p>\n'}, {'answer_id': 45721, 'author': 'Skizz', 'author_id': 1898, 'author_profile': 'https://Stackoverflow.com/users/1898', 'pm_score': 4, 'selected': False, 'text': '<p>I\'ve been using DevStudio for far too many years now and it always amazes me just how many  programmers don\'t know about the memory analysis tools that are available in the debug run time libraries. Here\'s a few links to get started with:</p>\n\n<p><a href="https://msdn.microsoft.com/en-us/library/aa297305(v=vs.60).aspx" rel="nofollow noreferrer">Tracking Heap Allocation Requests</a> - specifically the section on Unique Allocation Request Numbers</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/5at7yxcs.aspx" rel="nofollow noreferrer"><code>_CrtSetDbgFlag</code></a></p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/4wth1ha5.aspx" rel="nofollow noreferrer"><code>_CrtSetBreakAlloc</code></a></p>\n\n<p>Of course, if you\'re not using DevStudio then this won\'t be particularly helpful.</p>\n'}, {'answer_id': 45767, 'author': 'Dan Shield', 'author_id': 4633, 'author_profile': 'https://Stackoverflow.com/users/4633', 'pm_score': 1, 'selected': False, 'text': "<p>At least for MS VC++, the C Runtime library has several functions that I've found helpful in the past.  Check the MSDN help for the <code>_Crt*</code> functions.</p>\n"}, {'answer_id': 45943, 'author': 'Leon Timmermans', 'author_id': 4727, 'author_profile': 'https://Stackoverflow.com/users/4727', 'pm_score': 5, 'selected': False, 'text': '<p>In C++: use RAII. Smart pointers like <code>std::unique_ptr</code>, <code>std::shared_ptr</code>, <code>std::weak_ptr</code> are your friends.</p>\n'}, {'answer_id': 45951, 'author': 'jbl', 'author_id': 2353001, 'author_profile': 'https://Stackoverflow.com/users/2353001', 'pm_score': 0, 'selected': False, 'text': '<p>Valgrind is a nice option for Linux. Under MacOS X, you can enable the MallocDebug library which has several options for debugging memory allocation problems (see the malloc manpage, the "ENVIRONMENT" section has the relevant details). The OS X SDK also includes a tool called MallocDebug (usually installed in /Developer/Applications/Performance Tools/) that can help you to monitor usage and leaks.</p>\n'}, {'answer_id': 45963, 'author': 'Mark', 'author_id': 4405, 'author_profile': 'https://Stackoverflow.com/users/4405', 'pm_score': 2, 'selected': False, 'text': '<p>I think that there is no easy answer to this question.  How you might really approach this solution depends on your requirements.  Do you need a cross platform solution?  Are you using new/delete or malloc/free (or both)?  Are you really looking for just "leaks" or do you want better protection, such as detecting buffer overruns (or underruns)?</p>\n\n<p>If you are working on the windows side, the MS debug runtime libraries have some basic debug detection functionality, and as another has already pointed out, there are several wrappers that can be included in your source to help with leak detection.  Finding a package that can work with both new/delete and malloc/free obviously gives you more flexibility.</p>\n\n<p>I don\'t know enough about the unix side to provide help, although again, others have.</p>\n\n<p>But beyond just leak detection, there is the notion of detecting memory corruption via buffer overruns (or underruns).  This type of debug functionality is I think more difficult than plain leak detection.  This type of system is also further complicated if you are working with C++ objects because polymorhpic classes can be deleted in varying ways causing trickiness in determining the true base pointer that is being deleted.  I know of no good "free" system that does decent protection for overruns.  we have written a system (cross platform) and found it to be pretty challenging.</p>\n'}, {'answer_id': 46360, 'author': 'Thomas Kammeyer', 'author_id': 4410, 'author_profile': 'https://Stackoverflow.com/users/4410', 'pm_score': 2, 'selected': False, 'text': '<p>I\'d like to offer something I\'ve used at times in the past: a rudimentary leak checker which is source level and fairly automatic.\nI\'m giving this away for three reasons:</p>\n\n<ol>\n<li><p>You might find it useful.</p></li>\n<li><p>Though it\'s a bit krufty, I don\'t let that embarass me.</p></li>\n<li><p>Even though it\'s tied to some win32 hooks, that should be easy to alleviate.</p></li>\n</ol>\n\n<p>There are things of which you must be careful when using it:  don\'t do anything that needs to lean on <code>new</code> in the underlying code, beware of the warnings about cases it might miss at the top of leakcheck.cpp, realize that if you turn on (and fix any issues with) the code that does image dumps, you may generate a huge file.</p>\n\n<p>The design is meant to allow you to turn the checker on and off without recompiling everything that includes its header.  Include leakcheck.h where you want to track checking and rebuild once.  Thereafter, compile leakcheck.cpp with or without LEAKCHECK #define\'d and then relink to turn it on and off.  Including unleakcheck.h will turn it off locally in a file.  Two macros are provided:  CLEARALLOCINFO() will avoid reporting the same file and line inappropriately when you traverse allocating code that didn\'t include leakcheck.h.  ALLOCFENCE() just drops a line in the generated report without doing any allocation.</p>\n\n<p>Again, please realize that I haven\'t used this in a while and you may have to work with it a bit.  I\'m dropping it in to illustrate the idea.  If there turns out to be sufficient interest, I\'d be willing to work up an example, updating the code in the process, and replace the contents of the following URL with something nicer that includes a decently syntax-colored listing.</p>\n\n<p>You can find it here:  <a href="http://www.cse.ucsd.edu/~tkammeye/leakcheck.html" rel="nofollow noreferrer">http://www.cse.ucsd.edu/~tkammeye/leakcheck.html</a></p>\n'}, {'answer_id': 47358, 'author': 'DrPizza', 'author_id': 2131, 'author_profile': 'https://Stackoverflow.com/users/2131', 'pm_score': 0, 'selected': False, 'text': '<p>Detect:</p>\n\n<p>Debug CRT</p>\n\n<p>Avoid:</p>\n\n<p>Smart pointers, boehm GC</p>\n'}, {'answer_id': 50095, 'author': 'Dusty Campbell', 'author_id': 2174, 'author_profile': 'https://Stackoverflow.com/users/2174', 'pm_score': 6, 'selected': False, 'text': '<p>If you are using Visual Studio, Microsoft provides some useful functions for detecting and debugging memory leaks.</p>\n\n<p>I would start with this article:\n<a href="https://msdn.microsoft.com/en-us/library/x98tx3cf(v=vs.140).aspx" rel="noreferrer">https://msdn.microsoft.com/en-us/library/x98tx3cf(v=vs.140).aspx</a></p>\n\n<p>Here is the quick summary of those articles.  First, include these headers:</p>\n\n<pre><code>#define _CRTDBG_MAP_ALLOC\n#include &lt;stdlib.h&gt;\n#include &lt;crtdbg.h&gt;\n</code></pre>\n\n<p>Then you need to call this when your program exits:</p>\n\n<pre><code>_CrtDumpMemoryLeaks();\n</code></pre>\n\n<p>Alternatively, if your program does not exit in the same place every time, you can call this at the start of your program:</p>\n\n<pre><code>_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );\n</code></pre>\n\n<p>Now when the program exits all the allocations that were not free\'d will be printed in the Output Window along with the file they were allocated in and the allocation occurrence.</p>\n\n<p>This strategy works for most programs.  However, it becomes difficult or impossible in certain cases.  Using third party libraries that do some initialization on startup may cause other objects to appear in the memory dump and can make tracking down your leaks difficult.  Also, if any of your classes have members with the same name as any of the memory allocation routines( such as malloc ), the CRT debug macros will cause problems.</p>\n\n<p>There are other techniques explained in the MSDN link referenced above that could be used as well.</p>\n'}, {'answer_id': 60988, 'author': 'Josh Matthews', 'author_id': 3830, 'author_profile': 'https://Stackoverflow.com/users/3830', 'pm_score': 1, 'selected': False, 'text': '<p><a href="http://www.paulnettle.com/" rel="nofollow noreferrer">Paul Nettle\'s mmgr</a> is a long time favourite tool of mine.  You include mmgr.h in your source files, define TEST_MEMORY, and it delivers a textfile full of memory problems that occurred during a run of your app.</p>\n'}, {'answer_id': 70290, 'author': 'Weidenrinde', 'author_id': 11344, 'author_profile': 'https://Stackoverflow.com/users/11344', 'pm_score': 2, 'selected': False, 'text': '<p>For Linux: \n Try <a href="http://code.google.com/p/google-perftools/" rel="nofollow noreferrer">Google Perftools</a></p>\n\n<p>There are a lot of tools that do similar alloc/free counting, the pros of Goolge Perftools:</p>\n\n<ul>\n<li>Quite fast (in comparison to valgrind: very fast)</li>\n<li>Comes with nice graphical display of results</li>\n<li>Has other useful capabilities: cpu-profiling, memory-usage profiling...</li>\n</ul>\n'}, {'answer_id': 70304, 'author': 'Weidenrinde', 'author_id': 11344, 'author_profile': 'https://Stackoverflow.com/users/11344', 'pm_score': 1, 'selected': False, 'text': '<p>General Coding Guideline: </p>\n\n<ul>\n<li>Resources should be deallocated at the same "layer" (function/class/library) where they are allocated.</li>\n<li>If this is not possible, try to use some automatic deallocation (boost shared pointer...)</li>\n</ul>\n'}, {'answer_id': 70322, 'author': 'Dark Shikari', 'author_id': 11206, 'author_profile': 'https://Stackoverflow.com/users/11206', 'pm_score': 2, 'selected': False, 'text': "<p>The best defense against leaks is a program structure which minimizes the use of malloc.  This is not only good from a programming perspective, but also improves performance and maintainability.  I'm not talking about using other things in place of malloc, but in terms of re-using objects and keeping very explicit tabs on all objects being passed around rather than allocating willy-nilly like one often gets used to in languages with garbage collectors like Java.</p>\n\n<p>For example, a program I work on has a bunch of frame objects representing image data.  Each frame object has sub-data, which the frame's destructor frees.  The program keeps a list of all frames that are allocated, and when it needs a new one, checks a list of unused frame objects to see if it can re-use an existing one rather than allocate a new one.  On shutdown, it just iterates through the list, freeing everything.</p>\n"}, {'answer_id': 110970, 'author': 'Fabien Hure', 'author_id': 19912, 'author_profile': 'https://Stackoverflow.com/users/19912', 'pm_score': 2, 'selected': False, 'text': '<p>I would recommend using <a href="http://www.softwareverify.com/cpp/memory/index.html" rel="nofollow noreferrer">Memory Validator</a> from software verify.\nThis tool proved itself to be of invaluable help to help me track down memory leaks and to  improve the memory management of the applications i am working on. </p>\n\n<p>A very complete and fast tool.</p>\n'}, {'answer_id': 195373, 'author': 'Tal', 'author_id': 11287, 'author_profile': 'https://Stackoverflow.com/users/11287', 'pm_score': 3, 'selected': False, 'text': '<p>I’m amazed no one mentioned <a href="http://www.microsoft.com/downloadS/details.aspx?FamilyID=28bd5941-c458-46f1-b24d-f60151d875a3&amp;displaylang=en" rel="noreferrer">DebugDiag</a> for Windows OS.<br>\nIt works on release builds, and even at the customer site.<br>\n(You just need to keep your release version PDBs, and configure DebugDiag to use Microsoft public symbol server)</p>\n'}, {'answer_id': 195417, 'author': 'quinmars', 'author_id': 18687, 'author_profile': 'https://Stackoverflow.com/users/18687', 'pm_score': 0, 'selected': False, 'text': '<p>A nice malloc, calloc and reallloc replacement is rmdebug, it\'s pretty simple to use. It is much faster to then valgrind, so you can test your code extensively. Of course it has some downsides, once you found a leak you probably still need to use valgrind to find where the leak appears and you can only test mallocs that you do directly. If a lib leaks because you use it wrong, rmdebug won\'t find it.</p>\n\n<p><a href="http://www.hexco.de/rmdebug/" rel="nofollow noreferrer">http://www.hexco.de/rmdebug/</a></p>\n'}, {'answer_id': 387740, 'author': 'Hernán', 'author_id': 48026, 'author_profile': 'https://Stackoverflow.com/users/48026', 'pm_score': 3, 'selected': False, 'text': '<p>Visual Leak Detector is a very good tool, altough it does not supports the calls on VC9 runtimes (MSVCR90D.DLL for example). </p>\n'}, {'answer_id': 999442, 'author': 'paperhorse', 'author_id': 4498, 'author_profile': 'https://Stackoverflow.com/users/4498', 'pm_score': -1, 'selected': False, 'text': '<p><a href="http://en.wikipedia.org/wiki/Mtrace" rel="nofollow noreferrer">Mtrace</a> appears to be the standard built-in one for linux. The steps are :</p>\n\n<ol> <li>set up the environment variable MALLOC_TRACE in bash<br>\n<i>MALLOC_TRACE=/tmp/mtrace.dat</i><br>\n<i>export MALLOC_TRACE;</i></li>\n\n<li>Add <i>#include &lt;mcheck.h&gt;</i> to the top of you main source file</li>\n<li>Add <i>mtrace();</i> at the start of main and <i>muntrace();</i> at the bottom (before the return statement)</li>\n<li>compile your program with the -g switch for debug information</li>\n<li>run your program</li>\n<li>display leak info with <br><i>mtrace your_prog_exe_name /tmp/mtrace.dat</i><br>\n (I had to install the mtrace perl script first on my fedora system with <i>yum install glibc_utils</i>&nbsp;&nbsp;)</li>\n</ol>\n'}, {'answer_id': 999504, 'author': 'Einstein', 'author_id': 41898, 'author_profile': 'https://Stackoverflow.com/users/41898', 'pm_score': 1, 'selected': False, 'text': '<p>Memory debugging tools are worth their weight in gold but over the years I\'ve found that two simple ideas can be used to prevent most memory/resource leaks from being coded in the first place.</p>\n\n<ol>\n<li><p>Write release code immediatly after writing the acquisition code for the resources you want to allocate.  With this method its harder to "forget" and in some sense forces one to seriously think of the lifecycle of resources being used upfront instead of as an aside.</p></li>\n<li><p>Use return as sparringly as possible.  What is allocated should only be freed in one place if possible. The conditional path between acquisition of resource and release should be designed to be as simple and obvious as possible.</p></li>\n</ol>\n'}, {'answer_id': 1021266, 'author': 'tialaramex', 'author_id': 9654, 'author_profile': 'https://Stackoverflow.com/users/9654', 'pm_score': 1, 'selected': False, 'text': '<p>At the top of this list (when I read it) was valgrind. Valgrind is excellent if you are able to reproduce the leak on a test system. I\'ve used it with great success.</p>\n\n<p>What if you\'ve just noticed that the production system is leaking right now and you have no idea how to reproduce it in test? Some evidence of what\'s wrong is captured in the state of that production system, and it might be enough to provide an insight on where the problem is so you can reproduce it.</p>\n\n<p>That\'s where Monte Carlo sampling comes into the picture. Read Raymond Chen\'s blog article,\n“The poor man\'s way of identifying memory leaks” and then check out my implementation (assumes Linux, tested only on x86 and x86-64)</p>\n\n<p><a href="http://github.com/tialaramex/leakdice/tree/master" rel="nofollow noreferrer">http://github.com/tialaramex/leakdice/tree/master</a></p>\n'}, {'answer_id': 4340821, 'author': 'Sean', 'author_id': 25640, 'author_profile': 'https://Stackoverflow.com/users/25640', 'pm_score': 0, 'selected': False, 'text': '<p>Most memory profilers slow my large complex Windows application to the point where the results are useless.  There is one tool that works well for finding leaks in my application: UMDH - <a href="http://msdn.microsoft.com/en-us/library/ff560206%28VS.85%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ff560206%28VS.85%29.aspx</a></p>\n'}]
['https://Stackoverflow.com/questions/45627', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/123/']