From 8b520b4bedda6060a7c1b1a1bd14659241a4d4c3 Mon Sep 17 00:00:00 2001 From: Greg Bowne Date: Thu, 8 Feb 2024 17:34:20 -0800 Subject: [PATCH] updated malloc and extended heap --- main.c | 70 ++++++++++++++++++++++++++++++++++------------------------ 1 file changed, 41 insertions(+), 29 deletions(-) diff --git a/main.c b/main.c index 753b5bc..adecd3a 100644 --- a/main.c +++ b/main.c @@ -4,6 +4,7 @@ #define ALIGN4(s) (((((s)-1)>>2)<<2)+4) #define BLOCK_SIZE sizeof(struct block) +#define MINIMUM_BLOCK_SIZE 16 /// The memory block's header. struct block @@ -22,22 +23,27 @@ struct block* last = NULL; /// @returns The new memory block. struct block* extend_heap(size_t s) { - struct block* b = sbrk(0); + struct block* b = sbrk(0); - if (sbrk(BLOCK_SIZE + s) == (void*)-1) - return NULL; + // Ensure the allocated size is at least the minimum block size + if (s < MINIMUM_BLOCK_SIZE) { + s = MINIMUM_BLOCK_SIZE; + } - b->size = s; - b->prev = last; - b->next = NULL; - b->free = 0; + if (sbrk(BLOCK_SIZE + s) == (void*)-1) + return NULL; - if (last) - last->next = b; + b->size = s; + b->prev = last; + b->next = NULL; + b->free = 0; - last = b; + if (last) + last->next = b; - return b; + last = b; + + return b; } /// Finds the first block that will fit the given size. @@ -73,30 +79,36 @@ struct block* fragment_block(struct block* in, size_t s) /// @todo Fragmenting functionality. void* malloc(size_t size) { - struct block* b; + struct block* b; - size_t alignedSize = ALIGN4(size); + size_t alignedSize = ALIGN4(size); - if (first) - { - b = find_first(alignedSize); - if (!b) - b = extend_heap(alignedSize); - else if (b->size > BLOCK_SIZE + alignedSize) - b = fragment_block(b, alignedSize); - } - else - { - b = extend_heap(alignedSize); - if (!b) - return NULL; + // Enforce the minimum block size + if (alignedSize < MINIMUM_BLOCK_SIZE) { + alignedSize = MINIMUM_BLOCK_SIZE; + } - first = b; - } + if (first) + { + b = find_first(alignedSize); + if (!b) + b = extend_heap(alignedSize); + else if (b->size > BLOCK_SIZE + alignedSize) + b = fragment_block(b, alignedSize); + } + else + { + b = extend_heap(alignedSize); + if (!b) + return NULL; - return b + 1; + first = b; + } + + return b + 1; } + /// Will flag the provided memory as free and will defragment other blocks adjacent to it. /// @param [in] ptr The memory to flag as free. /// @note If all data after the provided memory is free, it will reduce the heap size.