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.
malloc_hook(3)allows you to globally interpose your ownmallocfunction. (There’s__realloc_hook__free_hooketc. as well, I’ve just left them out for simplicity.)printfmight callmalloc, which is why we undo the hook temporarily. Be careful of this if when you hookmallocin any way.