8
votes

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

2
It doesn't. Once an object is allocated, it's stuck in place until it dies. - n. 1.8e9-where's-my-share m.
what do you mean with defragmentation? a code example would help here. - blue
if you are concerned about memory fragmentation due to allocation/deallocation of a high number of small objects, the canonical way to deal with this is to use a memory pool to allocate your instances - try boost boost.org/doc/libs/1_47_0/libs/pool/doc/index.html - kfmfe04

2 Answers

9
votes

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.

3
votes

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