0

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.

scv
  • 490
  • 5
  • 14

5 Answers5

3

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.

Sumit Kumar
  • 160
  • 1
  • 5
  • 2
    Also you can use memory leak detector tool which provide profiling of heap usage like Valgrind (http://www.linuxprogrammingblog.com/using-valgrind-to-debug-memory-leaks). http://stackoverflow.com/questions/53426/memory-leak-detectors-for-c – Sumit Kumar Mar 18 '13 at 19:15
1

Using a wrapper creates overhead, for merely debugging purposes I prefer to hook malloc/calloc/free/etc and just dump information about what they are doing.

The benefit of this is that when you go to release (no need for debug stuff anymore) you simply remove the hooking functionality and that's it.

0

You have no way to do it with long directly. Wrap long with MyLong class and overload operator new for your class. This will track memory allocation in heap.

Narek
  • 38,779
  • 79
  • 233
  • 389
0

You can use a custom memory allocator to track memory allocation. See Doug Lea's one for a reference implementaion

user18428
  • 1,216
  • 11
  • 17
0

Intercept memory allocation routines, like it's shown in memory leak detection tool:

https://sourceforge.net/projects/diagnostic/ http://diagnostic.sourceforge.net/index.html

(Maybe even integrate it inside your application).

You will get not only malloc, realloc, free, but also all other allocations as well.

But please note that memory hooks are running in multithreaded environment, even even if your application is single threaded, there could be a lot of things happening in other threads as well.

Not well protected code can lead to deadlocks - see design of my code in readme.

TarmoPikaro
  • 4,723
  • 2
  • 50
  • 62