无法为malloc__hooks编译GNU示例

时间:2014-03-01 21:06:58

标签: c malloc hook

我复制并粘贴了示例malloc__hook: http://www.gnu.org/software/libc/manual/html_node/Hooks-for-Malloc.html

但是当我尝试编译它时,会出现错误:

hooks.c:17:8:错误:“__malloc_initialize_hook”的冲突类型限定符 在hooks.c:4:0中包含的文件中: /usr/include/malloc.h:170:38:注意:先前的'__malloc_initialize_hook'声明在这里

关于可能出错的任何想法?

这是我的代码:

/* Prototypes for __malloc_hook, __free_hook */
#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 *);
static void my_free_hook (void*, const void *);
static void test ();

/* Variables to save original hooks. */
static void *(*old_malloc_hook) (size_t, const void *);
static void *(*old_free_hook) (void*, 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;
    old_free_hook = __free_hook;
    __malloc_hook = my_malloc_hook;
    __free_hook = my_free_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);
    test();
    /* 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;
}

static void my_free_hook (void *ptr, const void *caller)
{
    /* Restore all old hooks */
    __malloc_hook = old_malloc_hook;
    __free_hook = old_free_hook;
    /* Call recursively */
    free (ptr);
    /* Save underlying hooks */
    old_malloc_hook = __malloc_hook;
    old_free_hook = __free_hook;
    /* printf might call free, so protect it too. */
    printf ("freed pointer %p\n", ptr);
    test();
    /* Restore our own hooks */
    __malloc_hook = my_malloc_hook;
    __free_hook = my_free_hook;
}


static void test (){
    printf("\ntest function called\n");
}

int main(void)
{
    char *p;
    p = malloc(10);
    free(p);
    return 0;
}

1 个答案:

答案 0 :(得分:0)

我相信你应该写:

void (*__MALLOC_HOOK_VOLATILE __malloc_initialize_hook) (void) = my_init_hook; 

而不是:

void (*__malloc_initialize_hook) (void) = my_init_hook;

我在Debian Wheezy上测试了它,现在编译它。