Yes, you can do similar things using LD_PRELOAD
; you’ll need to compile something like the following:
#include <dlcfn.h>
void *malloc(size_t size) {
static unsigned count = 0;
static void *(*real_malloc)(size_t) = NULL;
if (!real_malloc)
real_malloc = dlsym(RTLD_NEXT, "malloc");
if (++count == 100) {
count = 0;
return NULL;
}
return real_malloc (size);
}
as a shared object, e.g. with
gcc -shared -ldl -fPIC my_malloc.c -o libmy_malloc.so
Once you’ve done so, you can run your program like so:
LD_PRELOAD=/path/to/libmy_malloc.so ./my_program
and it will call the replacement malloc()
routine.
I imagine there are pre-built versions of the above with more debugging features than that, but you get the idea.
Oh, by the way, the above code is not tested (written in Stack Overflow). It is also not thread safe, and you need to be thread safe if replacing malloc(), so you’ll want to use pthread_once()
, and the pthread_mutex
APIs to fix that.