0

How can I automatically detect memory leaks in C++ in a portable way? I am looking for some sort of templating solution where I can just use a macro like NEW or DELETE to track creation and deletion. It has to work on Mac, Linux, and Windows.

yazz.com
  • 57,320
  • 66
  • 234
  • 385
  • 4
    You might consider replacing `new` and `delete` to collect the diagnostic information as well as track memory leaks.Good Reads: [Why should one replace default new and delete operators](http://stackoverflow.com/questions/7149461/why-should-one-replace-default-new-and-delete-operators) & [How should I write ISO C++ Standard conformant custom new and delete operators?](http://stackoverflow.com/questions/7194127/how-should-i-write-iso-c-standard-conformant-custom-new-and-delete-operators/).Note this is not really an automatic way. – Alok Save Feb 10 '12 at 06:33
  • 2
    The thing to realize is that you need not *detect* them in a portable way. If the code itself is portable, then detecting them on one platform (and squashing them) should rid the other platforms as well. – Matthieu M. Feb 10 '12 at 07:05
  • 1
    @MatthieuM.: Unfortunately, bugs are often compiler/platform-specific. – Alexey Frunze Feb 10 '12 at 08:39
  • 1
    @Alex: in which case you need to debug the specific impacted compiler/platform. – Matthieu M. Feb 10 '12 at 08:41

3 Answers3

3

There are a lot of tools available for that. E.g special libraries like dmalloc libraries like libfence. On Linux especially Valgrind is very useful.

so the best "bet" probably is that you get some malloc debug libraries source code and use it in all your developments.

Rüdiger Hanke
  • 6,215
  • 2
  • 38
  • 45
Friedrich
  • 5,916
  • 25
  • 45
2

I would suggest running valgrind on Linux and Mac OSX, and Microsoft Application Verifier on Windows. Both tools are free.

If you would like to do it in code you can keep track of allocations in a map. At program exit you simply check if the map is empty. If you use macros you can store the source line and file with the allocation record in the map. I do however believe that using a tool is simpler and better. They can help you with much more than tracking new/delete, and do not require changes to your code.

rasmus
  • 3,136
  • 17
  • 22
  • 1
    Most tools and the debug CRT such just track new/delete(/malloc/realloc/free), more or less. They're often unable to generate as clear of data as to the source of the leaks, which built-in tracking can. – ssube Feb 10 '12 at 06:42
  • The tools can supply where in the source the memory not freed was allocated. What more do you want? – rasmus Feb 10 '12 at 06:45
1

Valgrid is good - works on Linux & Mac. You might want to try Visual Leak detector for windows.

omggs
  • 1,163
  • 1
  • 11
  • 23