Firstly, I agree with the other posters that suggested the drain of resources. You really want to do this first.
We hope that the heap manager that you are currently using has a way to reset the actual total free space available on the heap (through all free ), as well as the total number of blocks that it is divided. If the average free block size is relatively small compared to the full free space on the heap, then you have a fragmentation problem. Alternatively, if you can reset the size of the largest free block and compare it with the total free space, this will be done with the same task. The largest free block will be small relative to the total free space available for all blocks if you use fragmentation.
To be very clear from the above, in all cases we are talking about free blocks on the heap, rather than allocated blocks on the heap. In any case, if the above conditions are not met, you really have some kind of leak.
So, once you have eliminated the leak, you might consider using a better distributor. The Doug Lea malloc suggested in the question is a very good distributor for general applications and very reliable in most cases. In other words, the time was checked to work very well for most applications. However, no algorithm is ideal for all applications, and any approach to the control algorithm may be violated by the correct pathological conditions against it.
Why do you have a fragmentation problem? - Sources of fragmentation problems are caused by the behavior of the application and are related to a significant lifetime in the same memory arena. That is, some objects are allocated and freed up regularly, while other types of objects are stored for long periods of time in the same heap. Think of longer life spans as knocking holes into larger areas of the arena and thereby preventing the pooling of adjacent blocks that have been freed.
To solve this problem, the best thing you can do is logically divide the heap into auxiliary arenas where the life spans are more similar. Essentially, you need a temporary heap and a permanent heap or heaps that group things of the same lifetime.
Some others have suggested a different approach to solving the problem, which is to try to make placement sizes more similar or identical, but this is less ideal because it creates a different type of fragmentation called internal fragmentation, which is actually wasted space that you have. allocating more memory in the block than you need.
In addition, with a good heap dispenser such as Doug Lea's, which makes the block sizes more similar, it is not necessary because the allocator will already use a two-stage bucketing scheme, which will make it completely unnecessary to artificially adjust the transferred sizes to malloc () - in fact, its manager heaps does this automatically for you much more reliably than the application can make adjustments.