With Linux/GCC/C++, I'd like to record something to stderr whenever malloc/free/new/delete are called. I'm trying to understand a library's memory allocations, and so I'd like to generate this output while I'm running unit tests. I use valgrind for mem leak detection, but I can't find an option to make it just log allocations.
Any ideas? I'm looking for the simplest possible solution. Recompiling the library is not an option.
I have not tested this myself, but I am pretty sure these would work:
Since you do not want to re-compile the library, giving meaningful output (vs. just "new called for 23 bytes") may require getting a stack trace. I remember using functions to navigate the stack, but I cannot find them right now. Maybe a call to system() and pstack(1) can do the trick.
You can re-define operator new and delete, and put this new definition ahead of the std c++ library. This may not capture the calls from containers and standard components that the library in question is using. This would require a relink.
Use can use LD_PRELOAD to change operator new and delete dynamically. This would not require a re-link if your application is dynamically linked.
Hope these pointers help, I am sorry I do not have a recipe.
You can trace calls to malloc/free with ltrace:
To trace new/delete calls without recompiling you will probably need to use something like LD_PRELOAD to override the calls with your own versions, this is precisely what LeakTracer does which might do what you want.
malloc_hook(3)
allows you to globally interpose your ownmalloc
function. (There's__realloc_hook
__free_hook
etc. as well, I've just left them out for simplicity.)printf
might callmalloc
, which is why we undo the hook temporarily. Be careful of this if when you hookmalloc
in any way.This article (scroll down to the bottom) provides a very clear and concise description of how to override the global
new
anddelete
operators in C++ (note that it doesn't provide an example fornew[]
, but it's similar in concept).As far as overriding malloc and free, since you're working on Linux and with GCC, the easiest method is to use
malloc_hook
andfree_hook
. Here is a very good description of how these functions work.