__free_hook没有按预期挂钩

时间:2015-04-24 08:13:16

标签: c malloc

来自this stackoverflow问题的所选答案。我决定将通话记录为免费通话。我做了一个记录free。但是free的来电似乎没有正确输出。

#include <malloc.h>

static void *(*old_malloc_hook)(size_t, const void *);

static void *new_malloc_hook(size_t size, const void *caller) {
    void *mem;

    __malloc_hook = old_malloc_hook;
    mem = malloc(size);
    fprintf(stderr, "%p: malloc(%zu) = %p\n", caller, size, mem);
    __malloc_hook = new_malloc_hook;

    return mem;
}

static void init_malloc_hooks(void) {
    old_malloc_hook = __malloc_hook;
    __malloc_hook = new_malloc_hook;
}

void (*volatile __malloc_initialize_hook)(void) = init_malloc_hooks;


static void (*old_free_hook)(void*, const void *);

static void new_free_hook(void* p, const void *caller) {
    __free_hook = old_free_hook;
    free(p);
    fprintf(stderr, "%p: free(%p)\n", caller, p);
    __free_hook = new_free_hook;
}

static void init_free_hooks(void) {
    old_free_hook = __free_hook;
    __free_hook = new_free_hook;
}

void (*volatile __free_initialize_hook)(void) = init_free_hooks;

1 个答案:

答案 0 :(得分:1)

_free_initialize_hook

永远不会被召唤。你需要删除

static void init_free_hooks(void) {
  old_free_hook = __free_hook;
  __free_hook = new_free_hook;
}

void (*volatile __free_initialize_hook)(void) = init_free_hooks;

在init_malloc_hooks中初始化两个钩子:

static void init_malloc_hooks(void) {
  old_malloc_hook = __malloc_hook;
  __malloc_hook = new_malloc_hook;
  old_free_hook = __free_hook;
  __free_hook = new_free_hook;
}