使用Malloc Hooks

时间:2008-11-06 18:03:02

标签: c malloc

我正在尝试使用malloc钩子来创建自定义函数my_malloc()。在我的主程序中,当我调用malloc()时我希望它调用my_malloc()有人可以给我一个如何在C中执行此操作的示例

5 个答案:

答案 0 :(得分:6)

答案 1 :(得分:5)

根据http://www.gnu.org/software/libtool/manual/libc/Hooks-for-Malloc.html,以下是如何使用GCC库执行此操作。

/* 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 ()
 {
   ...
 }

答案 2 :(得分:1)

如果你的函数直接调用sbrk,你可以简单地将它命名为malloc并确保它在库的malloc之前被链接。这适用于所有Unix类型的操作系统。对于Windows,请参阅Is there a way to redefine malloc at link time on Windows?

如果你的函数是库的malloc的包装器,那么Alex的#define建议就可以了。

答案 3 :(得分:1)

请注意,my_malloc_hook()解决方案在mutlithreaded程序中不起作用 - 请参阅http://www.phpman.info/index.php/man/malloc_hook/3

答案 4 :(得分:-3)

#undef malloc
#define malloc my_malloc

只需将其放在您需要执行的任何文件的顶部。