Resources | developer.brewmp.com Resources | developer.brewmp.com

Developer

resources

Using block allocators

Over-use of MALLOC() is a frequent cause of memory fragmentation. For example, when maintaining a set of data structures, the simple approach may be to MALLOC() memory for each instance as needed. However, this leads to many small blocks of memory littered throughout the heap.

A more efficient solution is to use block allocators. A block allocator is a chunk of memory (and a bit of code to manage it), that has been reserved specifically for a certain type of data. This chunk is preallocated with a size equal to some integer multiple of the size of that data. Whenever an instance of the block allocator's data type is needed, the memory is allocated from the block, rather than by using MALLOC(). If the block allocator is full, it can be resized using REALLOC().

Note that, by its design, a block allocator will always be fragmentation-free. There is no case in which the block allocator is not full, but can not satisfy a request. Because we use REALLOC() instead of MALLOC(), we also ensure that the data we put into it is compacted.

As a side effect, using block allocators can also help reduce total memory usage. Because we only allocate a single, large block from the heap, the heap manager will only create a single node header (typically 4-16 bytes each, depending on the heap implementation).

Applicability

Any application that maintains a set of instanced objects is a good candidate to use block allocators.