Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to replace default malloc by code

Tags:

malloc

I want to replace default malloc and add some statistics as well as leak detections and other behavious to malloc functions. I have seen some other imlementations like gperftool and jemlloc. They can replace the default malloc by linking with their static libraries. How can they do that? I would like to implement my custom malloc functions like that.

like image 319
gajia Avatar asked Aug 12 '26 01:08

gajia


1 Answers

You can wrap around the original malloc.

#include <dlfcn.h>

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

void initialize() {
    r_malloc = dlsym(RTLD_NEXT, "malloc");
}
void* malloc(size_t size) {
    //Do whatever you want
    return r_malloc(size);
}

But don't forget you must also wrap around calloc and realloc probably. And there are also less commonly used functions in the libc to allocate memory.

To wrap calloc you need to do a dirty hack because dlsym tries to allocate memory using calloc but doesn't really need it.

static void* __temporary_calloc(size_t x __attribute__((unused)), size_t y __attribute__((unused))) {
    return NULL;
}
static void* (*r_calloc)(size_t,size_t) = NULL;

and in the init function add this:

r_calloc = __temporary_calloc;
r_calloc = dlsym(RTLD_NEXT, "calloc");
like image 72
LtWorf Avatar answered Aug 15 '26 16:08

LtWorf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!