From 14d4e0ee674e0f2df74b7aee311e041f13efb8e3 Mon Sep 17 00:00:00 2001 From: karutoh Date: Thu, 8 Feb 2024 17:04:41 -0800 Subject: [PATCH] Fixed forward defragmenting, added reverse defragmenting, and added a line break on second printf. --- main.c | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/main.c b/main.c index c10d2f3..dad4fdb 100644 --- a/main.c +++ b/main.c @@ -9,6 +9,7 @@ struct block { size_t size; + struct block* prev; struct block* next; int free; }; @@ -27,6 +28,7 @@ struct block* extend_heap(size_t s) return NULL; b->size = s; + b->prev = last; b->next = NULL; b->free = 0; @@ -87,7 +89,6 @@ void* malloc(size_t size) /// 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. -/// @todo Reverse defragmenting. void free(void* ptr) { if (!ptr) @@ -96,15 +97,15 @@ void free(void* ptr) struct block* b = (struct block*)ptr - 1; b->free = 1; - struct block* link = b->next; + while (b->prev && b->prev->free) + b = b->prev; + while (b->next && b->next->free) { b->size += BLOCK_SIZE + b->next->size; - b->next = link->next; + b->next = b->next->next; } - // Reverse defragment here. - if (!b->next) brk(b); } @@ -118,10 +119,10 @@ int main() *b = 12; printf("Test 1: %i\n", *a); - printf("Test 2: %i", *b); + printf("Test 2: %i\n", *b); - free(b); free(a); + free(b); return 0; } \ No newline at end of file