diff --git a/src/small_allocator.c b/src/small_allocator.c index 4618d99..cc532f1 100644 --- a/src/small_allocator.c +++ b/src/small_allocator.c @@ -35,7 +35,7 @@ typedef struct { uint8_t* base; // backing store uint32_t size; // total size BlockHeader* heap_start; // first block - BlockHeader* next_fit; // next-fit pointer + BlockHeader* next_alloc; // start of free block search } SmallAllocator; /* --- Header helpers --- */ @@ -104,7 +104,7 @@ void small_allocator_init(SmallAllocator* a, void* backing_store, uint32_t size) first->prev = NULL_BLOCK; a->heap_start = first; - a->next_fit = first; + a->next_alloc = first; } static void maybe_split_block(SmallAllocator* a, BlockHeader* block, uint32_t size) @@ -147,6 +147,7 @@ static void merge_with_next(SmallAllocator* a, BlockHeader* block) block->next = next->next; BlockHeader* nextnext = block_from_offset(a, next->next); if (nextnext) nextnext->prev = bh_offset(a, block); + // note - caller have to adjust next_alloc on return } void* small_alloc(SmallAllocator* a, uint32_t size) @@ -156,7 +157,7 @@ void* small_alloc(SmallAllocator* a, uint32_t size) } size = ALIGN_UP(size); - BlockHeader* start = a->next_fit ? a->next_fit : a->heap_start; + BlockHeader* start = a->next_alloc ? a->next_alloc : a->heap_start; BlockHeader* curr = start; do { @@ -164,7 +165,7 @@ void* small_alloc(SmallAllocator* a, uint32_t size) maybe_split_block(a, curr, size); block_set_used(curr); BlockHeader *next = block_from_offset(a, curr->next); - a->next_fit = next ? next : a->heap_start;; + a->next_alloc = next ? next : a->heap_start;; return (uint8_t*)curr + sizeof(BlockHeader); } BlockHeader *next = block_from_offset(a, curr->next); @@ -194,9 +195,9 @@ void small_free(SmallAllocator* a, void* ptr) BlockHeader* prev = block_from_offset(a, block->prev); if (prev != NULL && block_is_free(prev)) { merge_with_next(a, prev); - a->next_fit = prev; + a->next_alloc = prev; } else { - a->next_fit = block; + a->next_alloc = block; } } @@ -213,7 +214,7 @@ void debug_alloc(const SmallAllocator* a) puts("--debug end--"); } -[[gnu::aligned(16)]] char buff[1023 * 1023]; +[[gnu::aligned(16)]] char buff[1023]; int main(void) { printf("bh size %zu\n", sizeof(BlockHeader)); @@ -223,15 +224,16 @@ int main(void) small_allocator_init(&a, buff, sizeof(buff)); debug_alloc(&a); - ptrs[0] = small_alloc(&a, 32); + ptrs[0] = small_alloc(&a, 1023-16*2 - 144); ptrs[1] = small_alloc(&a, 80); ptrs[2] = small_alloc(&a, 32); - small_free(&a, ptrs[1]); + debug_alloc(&a); + small_free(&a, ptrs[0]); ptrs[3] = small_alloc(&a, 12); ptrs[4] = small_alloc(&a, 12); debug_alloc(&a); - small_free(&a, ptrs[0]); + small_free(&a, ptrs[1]); small_free(&a, ptrs[2]); small_free(&a, ptrs[3]); small_free(&a, ptrs[4]);