在GNU C Library Reference Manual中,有一个示例程序(p.65),但我不知道这三个句子
是什么__malloc_hook = old_malloc_hook;
old_malloc_hook = __malloc_hook;
__malloc_hook = my_malloc_hook;
意思。尤其是第二个,谁能给我解释一下?谢谢。
static void *
my_malloc_hook (size_t size, const void *caller)
{
void *result;
/* Restore all old hooks */
__malloc_hook = old_malloc_hook;
__free_hook = old_free_hook;
/* Call recursively */
result = malloc (size);
/* Save underlying hooks */
old_malloc_hook = __malloc_hook;
old_free_hook = __free_hook;
/* printf might call malloc, so protect it too. */
printf ("malloc (%u) returns %p\n", (unsigned int) size, result);
/* Restore our own hooks */
__malloc_hook = my_malloc_hook;
__free_hook = my_free_hook;
return result;
}
我写了一个小程序来测试它:
#include <stdio.h>
#include <malloc.h>
/* Prototypes for our hooks. */
static void my_init_hook(void);
static void *my_malloc_hook(size_t, const void *);
/* Variables to save original hooks. */
static void *(*old_malloc_hook) (size_t, const void *);
/* Override initializing hook from the C library. */
void (*__malloc_initialize_hook) (void) = my_init_hook;
static void my_init_hook(void)
{
old_malloc_hook = __malloc_hook;
__malloc_hook = my_malloc_hook;
}
static void *my_malloc_hook(size_t size, const void *caller)
{
void *result;
/* Restore all old hooks */
__malloc_hook = old_malloc_hook;
printf("1: __malloc_hook = %x old_malloc_hook = %x\n", __malloc_hook, old_malloc_hook);
/* Call recursively */
result = malloc(size);
printf("2: __malloc_hook = %x old_malloc_hook = %x\n", __malloc_hook, old_malloc_hook);
/* Save underlying hooks */
old_malloc_hook = __malloc_hook;
printf("3: __malloc_hook = %x old_malloc_hook = %x\n", __malloc_hook, old_malloc_hook);
/* printf() might call malloc(), so protect it too. */
printf("malloc(%u) called from %p returns %p\n",
(unsigned int)size, caller, result);
/* Restore our own hooks */
__malloc_hook = my_malloc_hook;
printf("4: __malloc_hook = %x old_malloc_hook = %x\n", __malloc_hook, old_malloc_hook);
return result;
}
int main(void)
{
char *p;
p = malloc(10);
free(p);
return 0;
}
程序的结果是:
1: __malloc_hook = 0 old_malloc_hook = 0
2: __malloc_hook = 0 old_malloc_hook = 0
3: __malloc_hook = 0 old_malloc_hook = 0
malloc(10) called from 0xb7797f38 returns 0x932c008
4: __malloc_hook = 804849d old_malloc_hook = 0
但是现在我有更多的问题,为什么old_malloc_hook
都是0,在1,2,3中,为什么__malloc_hook
是0?我真的很困惑。帮我。