1MALLOC_HOOK(3) Linux Programmer's Manual MALLOC_HOOK(3)
2
3
4
6 __malloc_hook, __malloc_initialize_hook, __memalign_hook, __free_hook,
7 __realloc_hook, __after_morecore_hook - malloc debugging variables
8
10 #include <malloc.h>
11
12 void *(*__malloc_hook)(size_t size, const void *caller);
13
14 void *(*__realloc_hook)(void *ptr, size_t size, const void *caller);
15
16 void *(*__memalign_hook)(size_t alignment, size_t size, const void
17 *caller);
18
19 void (*__free_hook)(void *ptr, const void *caller);
20
21 void (*__malloc_initialize_hook)(void);
22
23 void (*__after_morecore_hook)(void);
24
26 The GNU C library lets you modify the behavior of malloc(), realloc(),
27 and free() by specifying appropriate hook functions. You can use these
28 hooks to help you debug programs that use dynamic memory allocation,
29 for example.
30
31 The variable __malloc_initialize_hook points at a function that is
32 called once when the malloc implementation is initialized. This is a
33 weak variable, so it can be overridden in the application with a defi‐
34 nition like the following:
35 void (*__malloc_initialize_hook)(void) = my_init_hook;
36 Now the function my_init_hook() can do the initialization of all hooks.
37
38 The four functions pointed to by __malloc_hook, __realloc_hook, __mema‐
39 lign_hook, __free_hook have a prototype like the functions malloc(),
40 realloc(), memalign(), free(), respectively, except that they have a
41 final argument caller that gives the address of the caller of malloc(),
42 etc.
43
44 The variable __after_morecore_hook points at a function that is called
45 each time after sbrk() was asked for more memory.
46
48 Here is a short example of how to use these variables.
49
50 #include <stdio.h>
51 #include <malloc.h>
52
53 /* Prototypes for our hooks. */
54 static void my_init_hook(void);
55 static void *my_malloc_hook(size_t, const void *);
56
57 /* Variables to save original hooks. */
58 static void *(*old_malloc_hook)(size_t, const void *);
59
60 /* Override initialising hook from the C library. */
61 void (*__malloc_initialize_hook) (void) = my_init_hook;
62
63 static void
64 my_init_hook(void) {
65 old_malloc_hook = __malloc_hook;
66 __malloc_hook = my_malloc_hook;
67 }
68
69 static void *
70 my_malloc_hook (size_t size, const void *caller) {
71 void *result;
72
73 /* Restore all old hooks */
74 __malloc_hook = old_malloc_hook;
75
76 /* Call recursively */
77 result = malloc (size);
78
79 /* Save underlying hooks */
80 old_malloc_hook = __malloc_hook;
81
82 /* `printf' might call `malloc', so protect it too. */
83 printf ("malloc(%u) called from %p returns %p\n",
84 (unsigned int) size, caller, result);
85
86 /* Restore our own hooks */
87 __malloc_hook = my_malloc_hook;
88
89 return result;
90 }
91
93 These functions are GNU extensions.
94
96 mallinfo(3), malloc(3), mcheck(3), mtrace(3)
97
98
99
100GNU 2002-07-20 MALLOC_HOOK(3)