Defragmentation of dynamically allocated memory in C++

动态分配内存的碎片整理(使用new和malloc操作符分配)如何在C ++中工作?


There is no defragmentation in the C++ heap because the application is free to keep pointers to allocated memory. Thus the heap manager cannot move memory around that is already allocated. The only "defragmentation" possible is if you free two adjacent blocks. Then the heap manager will combine the two blocks to a single larger free block that can be used for allocation again.


You might want to look into slab allocators. This won't be your silver bullet but for specific problems you may be able to relief the pressure. In a past project of mine we've had our own allocator written which was quite a complex affair but it certainly managed to get a grip on the issue.

While I agree with the other answers in general, sometimes there is hope in specific use cases. Such as similar objects that may be tackled with pool allocators: http://www.boost.org/doc/libs/1_53_0/libs/pool/doc/index.html

Also an interesting read are the allocators that come with boost interprocess: http://www.boost.org/doc/libs/1_53_0/doc/html/interprocess/allocators_containers.html#interprocess.allocators_containers.stl_allocators_adaptive

链接地址: http://www.djcxy.com/p/78720.html

上一篇: *是否可以在分配的内存上使用free()?

下一篇: 在C ++中动态分配内存的碎片整理