When a NEW or GETMEM statement is invoked, the allocation routine searches a block in this order of priorities:
When DISPOSE or FREEMEM is invoked, the given block is simply linked into the heap; it becomes the first free block.
To minimize the heap fragmentation, the memory blocks are allocated by chunks with a granularity of 4 bytes. The actual block size is the required size plus the memory needed for maintaining a “block size” at the beginning of the block (one byte for PIC16, two bytes for PIC18). If a block is greater than the required size rounded to the next 4 bytes boundary, it is split and the remaining bytes return to the heap.
Heap block memory format:
<block-size> is maintained in memory; the pointer returned by NEW or GETMEM is the address next to <block-size>.
When the memory block is freed by DISPOSE or FREEMEM, the given pointer is decremented to skip back to <block-size> and a consistency check is made between the size argument and the current block size; an error is generated if they don't match.