I would like to get the total memory allocated before and after I call a function in order to determine if I have freed everything correctly or not.
I’m doing this in C and I’m very rusty so forgive me if this is a naive question. I’m looking for something similar to the C# GC.GetTotalMemory(true) and this is in Windows for now.
Right now I am using PROCESS_MEMORY_COUNTERS_EX and GetProcessMemoryInfo(...), before and after calling the function but I can’t make heads or tails of the output because if I go into the function and comment out a call to free(...) then it will give me the same results (after is always larger). Here is what I have right now…
GetProcessMemoryInfo(hProc, &before, sizeof(before));
r = c->function();
GetProcessMemoryInfo(hProc, &after, sizeof(after));
if(r->result != 0) {
printf("error: %s\r\n", c->name);
printf(" %s\r\n", r->message);
printf(" %s (%d)\r\n", r->file, r->line);
failed++;
}
else if(after.PrivateUsage > before.PrivateUsage) {
printf("memory leak: %s\r\n", c->name);
printf(" %d kb\r\n", after.PrivateUsage - before.PrivateUsage);
failed++;
}
else succeeded++;
With a result like this:
after.PrivateUsage - before.PrivateUsage = 12288
If I go and comment out some calls to free I get the same result. How can I actually determine the current total size of memory that I have allocated using malloc?
I am, not aware of any c standard library functions which can help you achieve this. AFAIK, there don’t exist any. But you can use some sort of an hack, One should not use this in release builds but for debug and diagnostic purpose only.
You can use what I call malloc overloading in c. You do this with the help of macros.
You can write an wrapper function over
malloc, without modifying each and every instance in your code where the function is called then a simple macro shall suffice:Inside your own function you can collect the diagnostics in some global data structure, say a linked list.
For ex: It can maintain, buffer address being returned, the size for that corresponding allocation etc.
Similarly, you overload
free()and you can do the bookkeeping in there, Each buffer address passed in to the function can be checked against the list items and removed from the list as and when a match is found.At the end of the program the list contains entries for memory that was allocated but never freed, aka memory leaks. You can provide some api to fetch the diagnostic details from the list maintained whenever required.
You can often use this trick to write your own memory leak detector etc, for debugging purposes.