3

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.

gajia
  • 33
  • 1
  • 3
  • Just write your own `malloc` function with the correct signature. The linker will prefer your implementation to the standard C library. To allocate memory inside your function, use the API of your operating system (which is... ?). – GOTO 0 Jan 05 '13 at 04:04

1 Answers1

5

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");
Tim Rakowski
  • 97
  • 2
  • 7
LtWorf
  • 7,286
  • 6
  • 31
  • 45