Reputation: 2720
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.
Upvotes: 4
Views: 3772
Reputation: 1651
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...
Upvotes: 8
Reputation: 181280
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.
Upvotes: 1
Reputation: 111120
It's a little more complicated. Off the top-of-my-head:
my_malloc
, update the map with the size
argument.free
subtracting the size
(which you retrieve by looking up the pointer value) for that thread.Upvotes: 0