views:

559

answers:

3

Hello,

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.

A: 

It's a little more complicated. Off the top-of-my-head:

  • Create a map with the pointer value and memory size allocated for that pointer.
  • In your my_malloc, update the map with the size argument.
  • Write your own wrapper for free subtracting the size (which you retrieve by looking up the pointer value) for that thread.
dirkgently
+7  A: 

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...

paquetp
You allocated a memory area and returned 'allocated area address'+2*sizeof(int) so in myfree() the address you should pass to free() is 'the returned address from mymalloc()'-2*sizeof(int), which is 'imem'.
Leonardo Constantino
Nice solution, I like it! Thanks
Jérôme
+1  A: 

The only think I can think of (although you probably considered this) is keeping an allocation table whit these columns:

  • ThreadID (of course)
  • Pointer
  • Allocated size

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.

Pablo Santa Cruz