Go to the first, previous, next, last section, table of contents.


Storage Allocation Hooks

The GNU C library lets you modify the behavior of malloc, realloc, and free by specifying appropriate hook functions. You can use these hooks to help you debug programs that use dynamic storage allocation, for example.

The hook variables are declared in `malloc.h'.

Variable: __malloc_hook
The value of this variable is a pointer to function that malloc uses whenever it is called. You should define this function to look like malloc; that is, like:

void *function (size_t size)

Variable: __realloc_hook
The value of this variable is a pointer to function that realloc uses whenever it is called. You should define this function to look like realloc; that is, like:

void *function (void *ptr, size_t size)

Variable: __free_hook
The value of this variable is a pointer to function that free uses whenever it is called. You should define this function to look like free; that is, like:

void function (void *ptr)

You must make sure that the function you install as a hook for one of these functions does not call that function recursively without restoring the old value of the hook first! Otherwise, your program will get stuck in an infinite recursion.

Here is an example showing how to use __malloc_hook properly. It installs a function that prints out information every time malloc is called.

static void *(*old_malloc_hook) (size_t);
static void *
my_malloc_hook (size_t size)
{
  void *result;
  __malloc_hook = old_malloc_hook;
  result = malloc (size);
  /* printf might call malloc, so protect it too. */
  printf ("malloc (%u) returns %p\n", (unsigned int) size, result);
  __malloc_hook = my_malloc_hook;
  return result;
}

main ()
{
  ...
  old_malloc_hook = __malloc_hook;
  __malloc_hook = my_malloc_hook;
  ...
}

The mcheck function (see section Heap Consistency Checking) works by installing such hooks.


Go to the first, previous, next, last section, table of contents.