Reputation:
I am trying to use a malloc hook to create a custom function my_malloc(). In my main program when I call malloc() I want it to call my_malloc() can someone please give me an example on how to do this in C
Upvotes: 6
Views: 10718
Reputation:
Just note that my_malloc_hook() solution not really works in mutlithreaded program - see http://www.phpman.info/index.php/man/malloc_hook/3.
Upvotes: 1
Reputation: 2554
#undef malloc
#define malloc my_malloc
Just put that at the top of any of the files you need to do it for.
Upvotes: -3
Reputation: 1094
According to http://www.gnu.org/software/libtool/manual/libc/Hooks-for-Malloc.html, here's how to do this with the GCC libraries.
/* Prototypes for __malloc_hook, __free_hook */
#include <malloc.h>
/* Prototypes for our hooks. */
static void my_init_hook (void);
static void *my_malloc_hook (size_t, const void *);
static void my_free_hook (void*, const void *);
/* Override initializing hook from the C library. */
void (*__malloc_initialize_hook) (void) = my_init_hook;
static void
my_init_hook (void)
{
old_malloc_hook = __malloc_hook;
old_free_hook = __free_hook;
__malloc_hook = my_malloc_hook;
__free_hook = my_free_hook;
}
static void *
my_malloc_hook (size_t size, const void *caller)
{
void *result;
/* Restore all old hooks */
__malloc_hook = old_malloc_hook;
__free_hook = old_free_hook;
/* Call recursively */
result = malloc (size);
/* Save underlying hooks */
old_malloc_hook = __malloc_hook;
old_free_hook = __free_hook;
/* printf might call malloc, so protect it too. */
printf ("malloc (%u) returns %p\n", (unsigned int) size, result);
/* Restore our own hooks */
__malloc_hook = my_malloc_hook;
__free_hook = my_free_hook;
return result;
}
static void
my_free_hook (void *ptr, const void *caller)
{
/* Restore all old hooks */
__malloc_hook = old_malloc_hook;
__free_hook = old_free_hook;
/* Call recursively */
free (ptr);
/* Save underlying hooks */
old_malloc_hook = __malloc_hook;
old_free_hook = __free_hook;
/* printf might call free, so protect it too. */
printf ("freed pointer %p\n", ptr);
/* Restore our own hooks */
__malloc_hook = my_malloc_hook;
__free_hook = my_free_hook;
}
main ()
{
...
}
Upvotes: 6
Reputation: 13180
If your function calls sbrk directly you can simply call it malloc and make sure it gets linked in before the library's malloc. This works on all Unix type OSes. For windows see Is there a way to redefine malloc at link time on Windows?
If your function is a wrapper around the library's malloc, the #define suggestion by Alex will work.
Upvotes: 1
Reputation: 743
Did you look here? http://www.gnu.org/software/libtool/manual/libc/Hooks-for-Malloc.html
Upvotes: 6