Bourne
Bourne

Reputation: 1927

Defragmentation of dynamically allocated memory in C++

How does the defragmentation of dynamically allocated memory (allocated using the new and malloc operator ) work in C++?

Upvotes: 9

Views: 11512

Answers (2)

user2471020
user2471020

Reputation:

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

Upvotes: 4

Martin Liversage
Martin Liversage

Reputation: 106806

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.

Upvotes: 11

Related Questions