Home > Blogs > 30 C++ Tips in 30 Days: Tip # 10 avoiding heap fragmentation

30 C++ Tips in 30 Days: Tip # 10 avoiding heap fragmentation

By  Nov 29, 2007

Topics: Programming, C/C++

Frequent allocation and deallocation of dynamic memory leads to heap fragmentation, especially if the application is running for long periods and allocates small memory chunks. Learn what the dangers of heap fragmentation are and how you can avoid this problem.A highly fragmented heap may have a large number of free memory blocks but they are small and non-contiguous. Consider the following heap diagram in which minus signs indicate free memory blocks and plus signs indicate used memory blocks: 


This heap is highly fragmented. Allocating a memory block that contains 5 blocks (i.e., 5 consecutive minus signs) is impossible although the heap has a total of 12 free blocks.  Ideally, the heap should look like this:


To avoid heap fragmentation use dynamic memory allocating sparingly. In many cases, you can replace new and new[] with static or automatic storage, or use STL containers. Secondly, try to allocate and deallocate large chunks in every new and delete expression instead of allocating small chunks frequently. Using placement new to preallocate a large buffer and then slice that buffer into smaller units will reduce the risk of heap fragmentation.

Become an InformIT Member

Take advantage of special member promotions, everyday discounts, quick access to saved content, and more! Join Today.