main.c: #include #include #include #include
static void *(*old_malloc_hook)(size_t, const void*); static void (*old_free_hook)(void *, const void*); static void my_init_hook(void); static void *my_malloc_hook(size_t, const void*); static void my_free_hook(void*, const void*);
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) { #if 0 void *result; void *array[10]; char **strings; size_t size1;
__malloc_hook = old_malloc_hook; result = malloc(size); old_malloc_hook = __malloc_hook; printf("@@@%p+%p 0x%x\n",caller, result,(unsigned int)size); __malloc_hook = my_malloc_hook;
return result; #else void *result; void *array[10]; char **strings; unsigned int size1;
__malloc_hook = old_malloc_hook; size1 = backtrace(array, 10); strings = backtrace_symbols (array, size1); result = malloc(size); old_malloc_hook = __malloc_hook; printf ("Obtained %d stack frames.\n", size1); #if 0 unsigned int i; for (i = 0; i < size1; i++) printf ("%s\n", strings[i]); #endif
__malloc_hook = my_malloc_hook;
#if 1 switch(size1) { case 1: printf("@@@%p + %p 0x%x %s\n", \ caller, result, (unsigned int)size, \ strings[0]); break; case 2: printf("@@@%p + %p 0x%x %s %s\n", \ caller, result, (unsigned int)size, \ strings[0], strings[1]); break; case 3: printf("@@@%p + %p 0x%x %s %s %s\n", \ caller, result, (unsigned int)size, \ strings[0], strings[1], strings[2]); break; case 4: printf("@@@%p + %p 0x%x %s %s %s %s\n", \ caller, result, (unsigned int)size, \ strings[0], strings[1], strings[2], strings[3]); break; case 5: printf("@@@%p + %p 0x%x %s %s %s %s %s\n", \ caller, result, (unsigned int)size, \ strings[0], strings[1], strings[2], strings[3], strings[4]); break; case 6: printf("@@@%p + %p 0x%x %s %s %s %s %s %s\n", \ caller, result, (unsigned int)size, \ strings[0], strings[1], strings[2], strings[3], strings[4], strings[5]); break; case 7: printf("@@@%p + %p 0x%x %s %s %s %s %s %s %s\n", \ caller, result, (unsigned int)size, \ strings[0], strings[1], strings[2], strings[3], strings[4], strings[5], strings[6]); break; } #endif return result; #endif }
static void my_free_hook(void *ptr, const void *caller) { __free_hook = old_free_hook; free(ptr); old_free_hook = __free_hook; printf("@@@%p-%p\n", caller,ptr); __free_hook = my_free_hook; }
char *p[10];
int func1() { int i = 0; for(i=0;i<10;i++) { p[i] = (char *)malloc(i); } return 0; }
int func2() { int i = 0; for(i=0;i<9;i++) { free(p[i]); } return 0; }
int func3() { func1(); func2(); return 0; }
int main() { my_init_hook(); func1(); func2(); func3();
return 0; } |