Fragmentation occurs when objects of different sizes are allocated and deallocated in alternating orders and if lots of small objects are deallocated, following by lots of large objects being allocated.
This is best explained through an example. The following shows four steps we take in allocating and deallocating memory in a typical heap memory space:
The memory allocation takes place, as follows:
- We start with an empty heap space.
- We then allocate four objects on the heap, A, B, C, and D, each 64-bytes in size.
- At a later time, we deallocate two of the objects, A and C, freeing up 128 bytes.
- We then try to allocate ...