内存分配钩子__malloc_hook, __reallac_hook, __free_hook的使用

mem.h

#ifndef __MEM_H__
#define __MEM_H__

#include 
#include 

static void *(*old_malloc_hook)(size_t, const void*);
static void *(*old_realloc_hook)(void *ptr, size_t size, const void *caller);
static void (*old_free_hook)(void *, const void*);

static inline void *mem_malloc_hook(size_t size, const void *caller)
{
    void *result;
    __malloc_hook = old_malloc_hook;
    result = malloc(size);
    old_malloc_hook = __malloc_hook;
    __malloc_hook = mem_malloc_hook;
    printf("[malloc] size : [%u] at : [%p] caller : %p\n", (unsigned int)size, result, caller);
    return result;
}

static inline void *mem_realloc_hook(void *ptr, size_t size, const void *caller)
{
    void *result;
    __realloc_hook = old_realloc_hook;
    result = realloc(ptr, size);
    old_realloc_hook = __realloc_hook;
    printf("[realloc] size : [%u] at : [%p] caller : %p\n", (unsigned int)size, result, caller);
    __realloc_hook = mem_realloc_hook;
    return result;
}
 
static inline void mem_free_hook(void *ptr, const void *caller)
{
    __free_hook   = old_free_hook;
    free(ptr);
    old_free_hook = __free_hook;
    printf("[free] at : [%p] caller : %p\n", ptr, caller);
    __free_hook   = mem_free_hook;
}

static inline void init_mem_hook(void)
{
    old_malloc_hook = __malloc_hook;
    old_realloc_hook = __realloc_hook;
    old_free_hook   = __free_hook;
    __realloc_hook = mem_realloc_hook;
    __malloc_hook = mem_malloc_hook;
    __free_hook   = mem_free_hook;
}

#endif

main.c

#include "mem.h"

void (*__malloc_initialize_hook) (void) = init_mem_hook;

int main(int argc, char **argv)
{
    char *ptr = malloc(1024);
    ptr = realloc(ptr, 2048);
    free(ptr);
    return 0;
}


你可能感兴趣的:(linux编译技巧)