My goal is to write platform-independent free memory checker. Something like:
std::size_t before = MemoryAllocated();
do_stuff(); //some algorithm that uses malloc, free, new, delete, etc
std::size_t after = MemoryAllocated();
if( after != before )
printf( "ALARM! MEMORY LEAKS!\n" );
On POSIX there is mallinfo(), which provides pretty comprehensive free memory stats, one of the fields is uordblks, which seems to show exactly what I want. It includes the overhead - for instance it shows that new int on my machine allocates 32 bytes. But in the end of the day if you deallocaed everything - it shows 0, if you forgot something - it is non-zero.
On Windows there is _heapwalk(). It is a bit more complicated than mallinfo() - you need to iterate through heap chunks and compute the size yourself. And even after you did it, the result isn't quite what I expect:
int main()
{
std::cout << "start " << MemoryAllocated() << std::endl;
char *charr = new char[100];
std::cout << "after new char[100] " << MemoryAllocated() << std::endl;
int *pint = new int;
std::cout << "after new int " << MemoryAllocated() << std::endl;
delete[] charr;
std::cout << "after delete[] chars " << MemoryAllocated() << std::endl;
delete pint;
std::cout << "after delete int " << MemoryAllocated() << std::endl;
return 0;
}
results in:
start 26980
after new char[100] 31176
after new int 31180
after delete[] chars 31080
after delete int 31076
Looks like it allocates some initial 4 kbytes of memory for his internal needs on my first request to allocated memory, but then it shows current status accurately.
I tried to preallocate something before starting the real count - it doesn't help.
Can anybody hint me, how to do it properly on Windows?