Overriding ‘malloc’ using the LD_PRELOAD mechanism

I always do it this way:

#define _GNU_SOURCE

#include <stdio.h>
#include <dlfcn.h>

static void* (*real_malloc)(size_t)=NULL;

static void mtrace_init(void)
{
    real_malloc = dlsym(RTLD_NEXT, "malloc");
    if (NULL == real_malloc) {
        fprintf(stderr, "Error in `dlsym`: %s\n", dlerror());
    }
}

void *malloc(size_t size)
{
    if(real_malloc==NULL) {
        mtrace_init();
    }

    void *p = NULL;
    fprintf(stderr, "malloc(%d) = ", size);
    p = real_malloc(size);
    fprintf(stderr, "%p\n", p);
    return p;
}

Don’t use constructors, just initialize at first call to malloc. Use RTLD_NEXT to avoid dlopen. You can also try malloc hooks. Be aware that all those are GNU extensions, and probably wont work elsewhere.

Leave a Comment