帮忙解释__malloc_hook的用法
看了一段这个,感觉稀里糊涂的,求大侠们指点指点。。。。。
The GNU C library lets you modify the behavior of malloc, realloc, and free by specifying appropriate hook functions. You can use these hooks to help you debug programs that use dynamic storage allocation, for example.
The hook variables are declared in `malloc.h'.
Variable: __malloc_hook
The value of this variable is a pointer to function that malloc uses whenever it is called. You should define this function to look like malloc; that is, like:
void *function (size_t size)
Variable: __realloc_hook
The value of this variable is a pointer to function that realloc uses whenever it is called. You should define this function to look like realloc; that is, like:
void *function (void *ptr, size_t size)
Variable: __free_hook
The value of this variable is a pointer to function that free uses whenever it is called. You should define this function to look like free; that is, like:
void function (void *ptr)
You must make sure that the function you install as a hook for one of these functions does not call that function recursively without restoring the old value of the hook first! Otherwise, your program will get stuck in an infinite recursion.
Here is an example showing how to use __malloc_hook properly. It installs a function that prints out information every time malloc is called.
static void *(*old_malloc_hook) (size_t);
static void *
my_malloc_hook (size_t size)
{
void *result;
__malloc_hook = old_malloc_hook;
result = malloc (size);
__malloc_hook = my_malloc_hook;
printf ("malloc (%u) returns %p\n", (unsigned int) size, result);
return result;
}
main ()
{
...
old_malloc_hook = __malloc_hook;
__malloc_hook = my_malloc_hook;
...
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
就是用你自定义的函数来替代(一般是包装)malloc、realloc、free
回复 2# hellioncu
能详细解释下这段吗???
static void *(*old_malloc_hook) (size_t);
static void *
my_malloc_hook (size_t size)
{
void *result;
__malloc_hook = old_malloc_hook;
result = malloc (size);
__malloc_hook = my_malloc_hook;
printf ("malloc (%u) returns %p\n", (unsigned int) size, result);
return result;
}
main ()
{
...
old_malloc_hook = __malloc_hook;
__malloc_hook = my_malloc_hook;
...
}
static void *(*old_malloc_hook) (size_t); 定义函数指针old_malloc_hook
static void *
my_malloc_hook (size_t size)
{
void *result;
__malloc_hook = old_malloc_hook; 临时恢复原始malloc_hook,使得下面一句能调用到原始的 malloc
result = malloc (size);
__malloc_hook = my_malloc_hook; 恢复成自定义的my_malloc_hook
printf ("malloc (%u) returns %p\n", (unsigned int) size, result);
return result;
}
main ()
{
...
old_malloc_hook = __malloc_hook; 保存原始malloc_hook
__malloc_hook = my_malloc_hook; 替换当前malloc_hook为my_malloc_hook
...
}