How can I automatically detect memory leaks in C++ in a portable way?
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.
There are a lot of tools available for that. Eg 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.
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.
Valgrid is good - works on Linux & Mac. You might want to try Visual Leak detector for windows.
链接地址: http://www.djcxy.com/p/73038.html