From 3b38eddf5deaceb8948824ddda0b804052533b4e Mon Sep 17 00:00:00 2001 From: karutoh Date: Thu, 8 Feb 2024 16:44:26 -0800 Subject: [PATCH] Optimized code by adding last block global variable. --- main.c | 31 ++++++++++++------------------- 1 file changed, 12 insertions(+), 19 deletions(-) diff --git a/main.c b/main.c index 3821143..c10d2f3 100644 --- a/main.c +++ b/main.c @@ -13,13 +13,13 @@ struct block int free; }; -struct block* freeList = NULL; +struct block* first = NULL; +struct block* last = NULL; /// Extends heap memory upwards, towards zero. -/// @param [in] last The last block that the newly created block will link to. /// @param [in] s The size of the memory needed aligned by 4 bytes. /// @returns The new memory block. -struct block* extend_heap(struct block* last, size_t s) +struct block* extend_heap(size_t s) { struct block* b = sbrk(0); @@ -33,6 +33,8 @@ struct block* extend_heap(struct block* last, size_t s) if (last) last->next = b; + last = b; + return b; } @@ -41,24 +43,13 @@ struct block* extend_heap(struct block* last, size_t s) /// @returns The matching available memory block. struct block* find_first(size_t s) { - struct block* current = freeList; + struct block* current = first; while (current && (!current->free || current->size < s)) current = current->next; return current; } -/// Finds the last memory block in the linked list to attach a new block to. -/// @returns The last memory block. -struct block* find_last() -{ - struct block* current = freeList; - while (current && current->next) - current = freeList->next; - - return current; -} - /// Will find or allocate a memory block. /// @param [in] size The size of the memory block to request. /// @returns The requested memory on the heap. @@ -69,11 +60,13 @@ void* malloc(size_t size) size_t alignedSize = ALIGN4(size); - if (freeList) + if (first) { b = find_first(alignedSize); if (!b) - b = extend_heap(find_last(), alignedSize); + { + b = extend_heap(alignedSize); + } /* else Fragment here if possible. @@ -81,11 +74,11 @@ void* malloc(size_t size) } else { - b = extend_heap(NULL, alignedSize); + b = extend_heap(alignedSize); if (!b) return NULL; - freeList = b; + first = b; } return b + 1;