Designing something you take for granted, malloc and free

As previously mentioned, I needed to implement "malloc" and "free" in order to use cJSon.

To avoid conflict with the standard library names, and to reflect that these functions use their own data heap, I called them "heap_malloc" and "heap_free".

heap_init

I started with heap_init that initializes the character array that is used for the heap. I have initially thought that 256 bytes is enough, but redefining the macro will allow the heap to be resized, however, it will require a recompile (remember, I can't simply malloc a new buffer). There will be no "second call" protections on heap_init so calling it a second time will reclaim all allocations from the heap at the expense of invalidating all pointers.

heap_malloc

The basic algorithm for heap_malloc is to find the first block header that is big enough to fit the requested size, and add a new block into the list describing the requested size, while reducing the original block by the same size. So after initialization there is a single block, that is as large as the heap (minus the size of the header) and it is flagged as free. After the first heap_malloc, there will be two blocks in the list, one the size of the requested allocation that's flagged as in use, and one that is the remainder of the heap, flagged as free.

heap_free

heap_free will be responsible for returning the memory to the heap. I have decided that at the time of free efforts will be taken to reduce heap fragmentation by aggregating the block being free'd into any free blocks alongside it. If this is done every time that free is called, then all free space will be in as few blocks as possible and by using a doubly linked list, I won't need to traverse the list.

Subject: