#define N_THR 4 #include #include #include #include /* From http://www.gnu.org/software/libc/manual/html_node/Hooks-for-Malloc.html */ /* Prototypes for __malloc_hook, __free_hook */ #include void* (*old_malloc_hook) (size_t, const void *); /* Prototypes for our hooks. */ static void my_init_hook (void); static void *my_malloc_hook (size_t, 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; __malloc_hook = my_malloc_hook; } static void * my_malloc_hook (size_t size, const void *caller) { void *result; /* Restore all old hooks */ __malloc_hook = old_malloc_hook; /* Call recursively */ result = malloc (size); /* Save underlying hooks */ old_malloc_hook = __malloc_hook; /* printf might call malloc, so protect it too. */ printf ("malloc (%u) returns %p\n", (unsigned int) size, result); sleep(1); /* Restore our own hooks */ __malloc_hook = my_malloc_hook; return result; } /***************************/ /* Código de teste */ void* f_thread(void *v) { int thr_id = (int) v; int* s1; printf("Thread %d.\n", thr_id); s1 = malloc(sizeof(int)* 100 * thr_id); return 0; } int main() { pthread_t thr[N_THR]; int i; my_init_hook(); for (i = 0; i < N_THR; i++) pthread_create(&thr[i], NULL, f_thread, (void*) i+1); for (i = 0; i < N_THR; i++) pthread_join(thr[i], NULL); return 0; }