当前位置:  开发笔记 > 前端 > 正文

使用Malloc Hooks

如何解决《使用MallocHooks》经验,为你挑选了2个好方法。

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



1> 小智..:

你看到这儿了吗? http://www.gnu.org/software/libtool/manual/libc/Hooks-for-Malloc.html



2> Randy Stegba..:

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

/* Prototypes for __malloc_hook, __free_hook */
 #include 

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

推荐阅读
pan2502851807
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有