c++cmemory-managementmemory-fragmentation

Can "pragma pack 1" be helpful to avoid heap fragmentation?


In my program I see some resident size increase. I suppose it is because of heap fragmentation. So I am planning to use #pragma pack 1. Will it reduce the heap fragmentation?

Will it be having some other overheads?

Shall I go for it or not?


Solution

  • Packing structures probably won't have much affect on heap fragmentation. Heap fragmentation normally occurs when there is a repeating pattern of allocations and freeing of memory. There are two issues here, one issue is that the virtual address space gets fragmented, the other issue is that physical 4k pages end up with unused gaps, consuming increasing amounts of memory over time. Microsoft addresses the 4k page issue with it's .net framework that occasionally repacks memory, but does so by "pausing" a .net application during the repacks. I'm not sure how server apps that run 24 hours a day / 7 days a week deal with this without having to deal with the pauses, unless they occasionally fork off a new process to take over the server side and then close down the old process which would refresh the new process virtual address space with a new set of pages.