Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Per thread memory allocation

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.

like image 673
Jérôme Avatar asked Jan 23 '23 16:01

Jérôme


2 Answers

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

like image 175
paquetp Avatar answered Jan 26 '23 05:01

paquetp


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.

like image 43
Pablo Santa Cruz Avatar answered Jan 26 '23 07:01

Pablo Santa Cruz