How does the defragmentation of dynamically allocated memory (allocated using the new and malloc operator ) work in C++?
-
8It doesn't. Once an object is allocated, it's stuck in place until it dies.n. m. could be an AI– n. m. could be an AI2013-06-09 11:06:56 +00:00Commented Jun 9, 2013 at 11:06
-
2what do you mean with defragmentation? a code example would help here.blue– blue2013-06-09 11:07:46 +00:00Commented Jun 9, 2013 at 11:07
-
4if 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.htmlkfmfe04– kfmfe042013-06-09 11:13:15 +00:00Commented Jun 9, 2013 at 11:13
2 Answers
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.
9 Comments
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