钩子函数检查内存泄露

介绍:

  The GNU C Library lets you modify the behavior of malloc, realloc, and free by specifying appropriate hook functions.

使用:

  http://www.gnu.org/software/libc/manual/html_node/Hooks-for-Malloc.html

      参考:

  http://soft.zdnet.com.cn/software_zone/2009/1221/1567788.shtml

例子:

      代码

 1 #include <malloc.h>
 2 
 3 /* Prototypes for our hooks.  */
 4 static void my_init_hook (void);
 5 static void *my_malloc_hook (size_t, const void *);
 6 static void my_free_hook (void*, const void *);
 7 
 8 static void* (* old_malloc_hook) (size_t,const void *);
 9 static void (* old_free_hook)(void *,const void *);
10 
11 /* Override initializing hook from the C library. */
12 void (*__malloc_initialize_hook) (void) = my_init_hook;
13 
14 static void
15 my_init_hook (void)
16 {
17     old_malloc_hook = __malloc_hook;
18     old_free_hook = __free_hook;
19     __malloc_hook = my_malloc_hook;
20     __free_hook = my_free_hook;
21 }
22 
23 static void *
24 my_malloc_hook (size_t size, const void *caller)
25 {
26     void *result;
27     /* Restore all old hooks */
28     __malloc_hook = old_malloc_hook;
29     __free_hook = old_free_hook;
30     /* Call recursively */
31     result = malloc (size);
32     /* Save underlying hooks */
33     old_malloc_hook = __malloc_hook;
34     old_free_hook = __free_hook;
35     /* printf might call malloc, so protect it too. */
36     printf ("malloc (%u) returns %p
", (unsigned int) size, result);
37     /* Restore our own hooks */
38     __malloc_hook = my_malloc_hook;
39     __free_hook = my_free_hook;
40 return result;
41 }
42 
43 static void
44 my_free_hook (void *ptr, const void *caller)
45 {
46     /* Restore all old hooks */
47     __malloc_hook = old_malloc_hook;
48     __free_hook = old_free_hook;
49     /* Call recursively */
50     free (ptr);
51     /* Save underlying hooks */
52     old_malloc_hook = __malloc_hook;
53     old_free_hook = __free_hook;
54     /* printf might call free, so protect it too. */
55     printf ("freed pointer %p
", ptr);
56     /* Restore our own hooks */
57     __malloc_hook = my_malloc_hook;
58     __free_hook = my_free_hook;
59 }
60 
61 int
62 main (int arg,char **argv)
63 {
64     malloc(100);
65     malloc(100);
66     char* p = malloc(100);
67     free(p);
68     return 0;
69 }

       结果分析
    root@ubuntu:/home/linux/develop/mem_test/5# gcc test.c
    root@ubuntu:/home/linux/develop/mem_test/5# ./a.out
    malloc (100) returns 0x9b62008
    malloc (100) returns 0x9b62070
    malloc (100) returns 0x9b620d8
    freed pointer 0x9b620d8

原文地址:https://www.cnblogs.com/renhl/p/3304741.html