How can I track the memory allocations in C++, especially those done by new
/delete
. For an object, I can easily override the operator new
, but I'm not sure how to globally override all allocations so they go through my custom new
/delete
. This should be not a big problem, but I'm not sure how this is supposed to be done (#define new MY_NEW
?).
As soon as this works, I would assume it's enough to have a map somewhere of pointer/location of the allocation, so I can keep track of all allocations which are currently 'active' and – at the end of the application – check for allocations which have not been freed.
Well, this seems again like something that surely has been done several times at least, so any good library out there (preferably a portable one)?
Best Solution
I would recommend you to use
valgrind
for linux. It will catch not freed memory, among other bugs like writing to unallocated memory. Another option is mudflap, which tells you about not freed memory too. Use-fmudflap -lmudflap
options with gcc, then start your program withMUDFLAP_OPTIONS=-print-leaks ./my_program
.Here's some very simple code. It's not suitable for sophisticated tracking, but intended to show you how you would do it in principle, if you were to implement it yourself. Something like this (left out stuff calling the registered new_handler and other details).
We have to use our own allocator for our map, because the standard one will use our overridden operator new, which would result in an infinite recursion.
Make sure if you override operator new, you use the map to register your allocations. Deleting memory allocated by placement forms of new will use that delete operator too, so it can become tricky if some code you don't know has overloaded operator new not using your map, because operator delete will tell you that it wasn't allocated and use
std::free
to free the memory.Also note, as Pax pointed out for his solution too, this will only show leaks that are caused by code using our own defined operator new/delete. So if you want to use them, put their declaration in a header, and include it in all files that should be watched.