circular_heap
The circular heap is a dynamic memory allocator allocating buffers in a circular buffer. This puts a restriction on the user to free allocated buffers in the same order as they were allocated. This allocator is useful if you know the allocation order and need a low memory overhead on each allocated buffer and no memory fragmentation.
Below is an example of the internal state of a circular heap when buffers are allocated and freed.
After initialization begin, alloc and free have the same value. All memory is available for allocation.
begin alloc free end |-----------------------------------------------------|
Allocating a buffer increments alloc.
begin free alloc end |=========================|---------------------------|
Allocating another buffer increments alloc once again.
begin free alloc end |==========================================|----------|
Freeing the first buffer increments free to the position of the first alloc.
begin free alloc end |-------------------------|================|----------|
Allocating a buffer that is bigger than the available space between alloc and end results in a buffer starting at begin. The memory between the old alloc and end will be unused.
begin alloc free end |==================|------|================|oooooooooo|
Freeing the second buffer increments free to the position of the second alloc.
begin alloc free end |==================|-----------------------|oooooooooo|
Freeing the third buffer sets free to alloc. All memory is available for allocation once again.
alloc
- begin free end
----------------------------------|
- Done!
Source code: src/alloc/circular_heap.h
, src/alloc/circular_heap.c
Test code: tst/alloc/circular_heap/main.c
Test coverage: src/alloc/circular_heap.c
alloc/circular_heap.h