code_junkie

Outputting to stderr whenever malloc/free is called

Nov 12th, 2011
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.82 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <malloc.h>
  3.  
  4. static void *(*old_malloc_hook)(size_t, const void *);
  5.  
  6. static void *new_malloc_hook(size_t size, const void *caller) {
  7. void *mem;
  8.  
  9. __malloc_hook = old_malloc_hook;
  10. mem = malloc(size);
  11. fprintf(stderr, "%p: malloc(%zu) = %pn", caller, size, mem);
  12. __malloc_hook = new_malloc_hook;
  13.  
  14. return mem;
  15. }
  16.  
  17. static void init_my_hooks(void) {
  18. old_malloc_hook = __malloc_hook;
  19. __malloc_hook = new_malloc_hook;
  20. }
  21.  
  22. void (*__malloc_initialize_hook)(void) = init_my_hooks;
  23.  
  24. printf
  25.  
  26. #include <stdlib.h>
  27.  
  28. int main (void)
  29. {
  30. void *ptr = malloc(10);
  31. free(ptr);
  32.  
  33. return 0;
  34. }
  35.  
  36.  
  37. $ g++ test.cpp -o test
  38. $ ltrace -e malloc,free ./test
  39. malloc(10) = 0x804a008
  40. free(0x804a008) = <void>
  41. +++ exited (status 0) +++
Add Comment
Please, Sign In to add comment