Designing Custom Memory Allocator : free()

geekgirldecodes
HowsOfCoding
3 min readJan 12, 2022

--

This is the second blog on custom memory allocator design. In the first blog, we discussed about using a circular list as a bookkeeping mechanism that maintains a linked list of free or available blocks to help with allocation. In this blog, we will cover the details of a corresponding free() API design.

Like malloc() , even free() shall update the free list maintained to reflect the available blocks. When free() is called, it checks if the blocks adjacent to
the freed block (left or right sides), are also free :
• If so, adjacent free blocks are merged (coalesced) into a single, larger free block.
• Otherwise, the freed block is just added to the free list.

Implementation

To implement a free() API, we simply need to manipulate (or update) data structure (namely free list) maintained by the memory allocator to reflect free blocks.

There are three main cases to be handled in this list update process:

  1. if the free() is called upon address at the end of the free list.
  2. if free() is called on an address that points to a chunk that can be coalesced into, on the right side.
  3. if free() is called on an address that points to a chunk that can be coalesced into, on the left side.

Complexity

Time complexity

  • free() involves just adding an entry to free list- it takes constant time O(1).

In the next blog in this series, we will look at a modified version of malloc() and free() that support “aligned” allocations.

If you liked reading this blog, don’t forget to drop some claps below to help reach more people. Thank you! :)

--

--

geekgirldecodes
HowsOfCoding

Full-time engineer, part-time procrastinator — always overdosing on coffee! 8). Author at publication : @howsofcoding