1

Im trying to measure heap fragmentation, I will use this formula :

Fragmentation = 1 - (LargestFreeBlockAvailable / TotalFreeMemory)

The tricky part is to find the largest free blocks.

I have found this code which allow me to show all blocks in the heap : https://learn.microsoft.com/en-us/windows/win32/toolhelp/traversing-the-heap-list

I'm trying to create fragmentation allocating and deallocating larger and larger blocks :

std::allocator<char> alloc;
char * tmp = alloc.allocate(100);
    alloc.deallocate(tmp,100);
    tmp = alloc.allocate(200);
    alloc.deallocate(tmp,200);
    tmp = alloc.allocate(300);
    alloc.deallocate(tmp, 300);
    tmp = alloc.allocate(400);
    alloc.deallocate(tmp, 400);
    tmp = alloc.allocate(1000);
    alloc.deallocate(tmp, 1000);
    tmp = alloc.allocate(2000);
    alloc.deallocate(tmp, 2000);
    tmp = alloc.allocate(3000);
    alloc.deallocate(tmp, 3000);
    tmp = alloc.allocate(5000);
    alloc.deallocate(tmp, 5000);
    alloc.allocate(15000);

But I see no fragmentation when I run run the program, There is only one free block which correspond to the available memory left : Results

It's like if the block I freed previously where merged to this big last block... There arent any "hole" in the heap which would indicate fragmentation. Is anyone aware of the mechanism that occurs which avoid the fragmentation? Maybe im doing it wrong to create the fragmentation ?

Thank you in advance. Sorry for bad english.

trincot
  • 317,000
  • 35
  • 244
  • 286
Wololo
  • 11
  • 2
  • Hi Wololo - can you please be clearer about the required solution? What are you actually trying to accomplish? Also, try to include results (test, images, and all) within the post – Ruslan Jul 27 '20 at 14:08
  • 1
    Hello Ruslan, thank you for your attention. Is it more clear like this? – Wololo Jul 27 '20 at 14:30
  • It's not completely clear what you are doing here (what is `alloc` here), but it does appear that you are allocating progressively larger blocks of memory but then immediately freeing them again. In any sane memory manager this would cause the newly freed block to merge with the one it came from and hence would not cause fragmentation. – 500 - Internal Server Error Jul 27 '20 at 14:53
  • alloc here is the standard allocator for the STL. Oh ok i made a stupid mistake here thank you. If I do it this way do you agree that this should create fragmentation? ```char* tmp = alloc.allocate(100); alloc.allocate(1000); //random alloc alloc.allocate(15000); alloc.deallocate(tmp, 100); ``` Just allocating random size between the first allocation and his deallocation. – Wololo Jul 27 '20 at 15:07

0 Answers0