scv scv - 1 month ago 16
C Question

tracking dynamic memory allocation in c/c++

In c or c++, Is there any way to keep track of dynamically allocated memory. Say i have code like this

void somefunction(some arguments,long mc){
//allocate b bytes of memory using malloc,calloc or new
mc += b;


//allocate once again, say p bytes
mc += p;


//deallocate q bytes using delete or free()
mc -= q;

print "mc bytes allocated at this point";

}


one could declare mc as global and use it in all functions. The problem is when memory is deallocated, there is no way of knowing how much memory was just deallocated so how does one update mc in this case.

Answer

Create wrapper function for malloc(), calloc and free(). In malloc/calloc allocate extra word size to maintain how much memory is to allocate and also sum up the bytes allocated in mc. when doing free, read first header bytes to know how much memory is to be freed and decrease the same size from mc.

Comments