Tracking memory leaks with the memory manager's hook function
Please specify the source and the author's contact information at time of download
Author contact information: Li Xianjing <xianjimli at hotmail Dot com>
As a C programmer under Linux, I always used to run the program with Valgrind after the unit test passed, to see if there were any memory leaks and memory out of bounds. Unfortunately, sometimes valgrind does not work very well, like DIRECTFB-based multi-process programs under Valgrind can not afford to run, then we could use the Memory manager hook function to track memory leaks.
The GLIBC provides a hook function for the memory manager that allows you to monitor/change the behavior of memory management functions. In fact, GLIBC has used this mechanism to realize the function of memory leak detection, provided mtrace/muntrace two functions and mtrace tools, just not very good, one is slow, two is no backtrace. What's worse is that I can't find it on Fedora 7 anymore, so I have to write a:
Record allocation/release operations first:
/**//*memory_trace.c*/
#include <execinfo.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <malloc.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
static void Memory_trace_init (void);
static void Memory_trace_deinit (void);
static void *my_malloc_hook (size_t size, const void* PTR);
static void My_free_hook (void* ptr, const void* caller);
static void *my_realloc_hook (void *ptr, size_t size, const void *caller);
static void *my_malloc_hook (size_t size, const void* PTR);
static void My_free_hook (void* ptr, const void* caller);
static void *my_realloc_hook (void *ptr, size_t size, const void *caller);
static void * (*old_malloc_hook) (size_t size, const void* PTR);
static void (*old_free_hook) (void* ptr, const void* caller);
static void * (*old_realloc_hook) (void *ptr, size_t size, const void *caller);
#define BACK_TRACE_DEPTH 8
#define CACHE_SIZE 512
static file* g_memory_trace_fp = NULL;
static int g_memory_trace_cache_used = 0;
/**//*additional 3 Items:alloc/free Addr size*/
Static void* g_memory_trace_cache[cache_size][back_trace_depth + 3];
static void Memory_trace_flush (void);
static void Memory_trace_write (int alloc, void* addr, int size);
static void Memory_trace_backup (void)
... {
Old_malloc_hook = __malloc_hook;
Old_free_hook = __free_hook;
Old_realloc_hook = __realloc_hook;
Return
}
static void Memory_trace_hook (void)
... {
__malloc_hook = My_malloc_hook;
__free_hook = My_free_hook;
__realloc_hook =