1 .\" Copyright 2002 Walter Harms (walter.harms@informatik.uni-oldenburg.de)
2 .\" Distributed under GPL
3 .\" Heavily based on glibc documentation
4 .\" Polished, added docs, removed glibc doc bug, 2002-07-20, aeb
5 .TH MALLOC_HOOK 3 2002-07-20 "GNU" "Linux Programmer's Manual"
7 __malloc_hook, __malloc_initialize_hook,
8 __memalign_hook, __free_hook, __realloc_hook,
9 __after_morecore_hook \- malloc debugging variables
12 .BR "#include <malloc.h>"
14 .BI "void *(*__malloc_hook)(size_t " size ,
15 .BI "const void *" caller );
17 .BI "void *(*__realloc_hook)(void *" ptr ,
19 .BI "const void *" caller );
21 .BI "void *(*__memalign_hook)(size_t " alignment ,
23 .BI "const void *" caller );
25 .BI "void (*__free_hook)(void *" ptr ,
26 .BI "const void *" caller );
28 .BI "void (*__malloc_initialize_hook)(void);"
30 .BI "void (*__after_morecore_hook)(void);"
32 The GNU C library lets you modify the behavior of
37 by specifying appropriate hook functions. You can use these hooks
38 to help you debug programs that use dynamic memory allocation,
42 .B __malloc_initialize_hook
43 points at a function that is called once when the malloc implementation
44 is initialized. This is a weak variable, so it can be overridden in
45 the application with a definition like the following:
48 void (*__malloc_initialize_hook)(void) = my_init_hook;
53 can do the initialization of all hooks.
55 The four functions pointed to by
60 have a prototype like the functions
65 respectively, except that they have a final argument
67 that gives the address of the caller of
72 .B __after_morecore_hook
73 points at a function that is called each time after
75 was asked for more core.
77 Here a short example how to use these variables.
83 /* Prototypes for our hooks. */
84 static void my_init_hook(void);
85 static void *my_malloc_hook(size_t, const void *);
87 /* Variables to save original hooks. */
88 static void *(*old_malloc_hook)(size_t, const void *);
90 /* Override initialising hook from the C library. */
91 void (*__malloc_initialize_hook) (void) = my_init_hook;
95 old_malloc_hook = __malloc_hook;
96 __malloc_hook = my_malloc_hook;
100 my_malloc_hook (size_t size, const void *caller) {
103 /* Restore all old hooks */
104 __malloc_hook = old_malloc_hook;
106 /* Call recursively */
107 result = malloc (size);
109 /* Save underlying hooks */
110 old_malloc_hook = __malloc_hook;
112 /* `printf' might call `malloc', so protect it too. */
113 printf ("malloc(%u) called from %p returns %p\n",
114 (unsigned int) size, caller, result);
116 /* Restore our own hooks */
117 __malloc_hook = my_malloc_hook;