I am working on a trace tool for multithread applications, more especially about memory allocation.
I would like a per thread memory allocation. I know that when a thread do a malloc, the memory used is the global heap. I would like to trace which thread allocated how much memory.
I did a wrapper upon malloc, incrementing values each time there is a malloc as:
void *mymalloc(size_t size) {
mem_used[thread_id] += size;
return malloc(size);
}
It works well. The problem is with free
method, which does not return how much memory is released.
Don't take into account my solution, it is just to show what I tried.
EDIT:
As mentionned above, keeping my own table is a too heavy method.
how about changing mymalloc to do:
int* mymem = malloc(size + sizeof(int)*2);
mymem[0] = thread_id;
mymem[1] = size;
mem_used[thread_id] += size;
return &mymem[2].
Then, in myfree(void* mem), you:
void myfree(void* mem)
{
int* imem = (int*)(mem - sizeof(int)*2);
int thread_id = imem[0];
int size = imem[1];
mem_used[thread_id] -= size;
free(imem);
}
this can be optimized, but I hope you get the idea...
The only think I can think of (although you probably considered this) is keeping an allocation table whit these columns:
Then, you will have to use your own malloc and free functions to do the actual mallocing and freeing, but also keeping the allocation table updated.
Is this for debugging purposes? Because otherwise, the overhead of maintaining this table can be significant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With