Portable way to detect heap fragmentation in c++ at runtime?

I’m writing a qt-based c++ application and i need to be able to detect memory fragmentation in order to check if the current system can actually sustain the memory load: the program load a big image (15/21 megapixels are the norm) in memory and then perform some filtering on it (w/ sparse matrices).
For instance, i’m having memory fragmentation problem in Windows and VMMap has been very helpful in this: the problem was some DLLs (Wacom tablet “wintab32.dll” and the UltraMon app) doesn’t get relocated so are splitting the address space at the 0x10000000-0x30000000 VA of the process.

I want to provide the application with some sort of awareness toward the fragmentation problem and wondering if a cross-platform (linux/mac/win32) approach giving the information VMMAP gives already exist.

Short answer: There is no portable way.

Longer answer: How the heap is implemented and how it works is an implementation detail of your implementation that widely differs between platforms, std libraries, and operating systems. You’ll have to create a different version for each implementation – provided, the implementation gives you an API to hook into it. (Which I think should be the case for the three platforms you target.)

I think you are overly pessimistic. 21 Megapixels, even assuming a colordepth of 16 bits and an equal-sized alphachannel would take only 168 MB. The available address space on a 32 bit system is measured in gigabytes.

Would this do what you need?

bool is_contiguous_freestore_available(size_t max)
   char* tst = new(std::nothrow) char[max];
   if (tst == null)
      return false;

   delete[] tst;
   return true;

Leave a Comment