Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

how to replace default malloc by code

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can wrap around the original malloc.

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(bsize);
}

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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...