Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Outputting to stderr whenever malloc/free is called

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.

like image 241
twk Avatar asked Nov 28 '22 05:11

twk


1 Answers

You can trace calls to malloc/free with ltrace:

#include <stdlib.h>

int main (void)
{
  void *ptr = malloc(10);
  free(ptr);

  return 0;
}


$ g++ test.cpp -o test
$ ltrace -e malloc,free ./test
malloc(10)                                       = 0x804a008
free(0x804a008)                                  = <void>
+++ exited (status 0) +++

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.

like image 173
Robert Gamble Avatar answered Dec 06 '22 09:12

Robert Gamble