如何用代码替换默认的malloc [英] how to replace default malloc by code
问题描述
我想替换默认的malloc并添加一些统计信息以及泄漏检测和其他对malloc函数的行为.我还看到了其他一些实现,例如gperftool和jemlloc.他们可以通过链接其静态库来替换默认的malloc.他们该怎么做?我想实现我的自定义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.
推荐答案
您可以包装原始的malloc.
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);
}
但是请不要忘记,您还必须包装calloc并可能重新分配.而且,libc中还有一些不常用的函数来分配内存.
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.
要包装calloc,您需要做一个肮脏的技巧,因为dlsym尝试使用calloc分配内存,但实际上并不需要它.
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;
,然后在init函数中添加以下内容:
and in the init function add this:
r_calloc = __temporary_calloc;
r_calloc = dlsym(RTLD_NEXT, "calloc");
这篇关于如何用代码替换默认的malloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!