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

Developer

resources

Block allocators

Overuse of MALLOC() is a frequent cause of memory fragmentation. An example is to MALLOC() memory for each instance as needed when maintaining a set of data structures. This leads to many small blocks of memory littered throughout the heap. A more efficient strategy is to design and implement block allocators within the application to manage memory.

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 pre-allocated 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 design, a block allocator will always be fragmentation-free. There is no case in which the block allocator is not full, but cannot satisfy a request. Using REALLOC() instead of MALLOC() ensures that the data put into it is compacted. As a side effect, using block allocators can also help reduce total memory usage. When allocating 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). Any application that maintains a set of instanced objects is a good candidate to use block allocators.