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.
38 You can use these hooks
39 to help you debug programs that use dynamic memory allocation,
43 .B __malloc_initialize_hook
44 points at a function that is called once when the malloc implementation
46 This is a weak variable, so it can be overridden in
47 the application with a definition like the following:
50 void (*__malloc_initialize_hook)(void) = my_init_hook;
55 can do the initialization of all hooks.
57 The four functions pointed to by
62 have a prototype like the functions
67 respectively, except that they have a final argument
69 that gives the address of the caller of
74 .B __after_morecore_hook
75 points at a function that is called each time after
77 was asked for more memory.
79 These functions are GNU extensions.
81 Here is a short example of how to use these variables.
87 /* Prototypes for our hooks. */
88 static void my_init_hook(void);
89 static void *my_malloc_hook(size_t, const void *);
91 /* Variables to save original hooks. */
92 static void *(*old_malloc_hook)(size_t, const void *);
94 /* Override initializing hook from the C library. */
95 void (*__malloc_initialize_hook) (void) = my_init_hook;
100 old_malloc_hook = __malloc_hook;
101 __malloc_hook = my_malloc_hook;
105 my_malloc_hook(size_t size, const void *caller)
109 /* Restore all old hooks */
110 __malloc_hook = old_malloc_hook;
112 /* Call recursively */
113 result = malloc(size);
115 /* Save underlying hooks */
116 old_malloc_hook = __malloc_hook;
118 /* `printf' might call `malloc', so protect it too. */
119 printf("malloc(%u) called from %p returns %p\\n",
120 (unsigned int) size, caller, result);
122 /* Restore our own hooks */
123 __malloc_hook = my_malloc_hook;