From 0b25fa434f3b0bd54430345501f409f47b06f59f Mon Sep 17 00:00:00 2001 From: karutoh Date: Thu, 8 Feb 2024 17:24:49 -0800 Subject: [PATCH] Added memory block fragmenting. --- main.c | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/main.c b/main.c index dad4fdb..753b5bc 100644 --- a/main.c +++ b/main.c @@ -52,6 +52,21 @@ struct block* find_first(size_t s) return current; } +struct block* fragment_block(struct block* in, size_t s) +{ + size_t totalSize = BLOCK_SIZE + s; + struct block* b = (struct block*)((char*)(in + 1) + (in->size - totalSize)); + b->size = s; + b->prev = in; + b->next = in->next; + b->free = 0; + + in->size -= totalSize; + in->next = b; + + return b; +} + /// 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. @@ -66,13 +81,9 @@ void* malloc(size_t size) { b = find_first(alignedSize); if (!b) - { b = extend_heap(alignedSize); - } - /* - else - Fragment here if possible. - */ + else if (b->size > BLOCK_SIZE + alignedSize) + b = fragment_block(b, alignedSize); } else { @@ -95,6 +106,9 @@ void free(void* ptr) return; struct block* b = (struct block*)ptr - 1; + if (b->free) + return; + b->free = 1; while (b->prev && b->prev->free) @@ -124,5 +138,7 @@ int main() free(a); free(b); + int* c = (int*)malloc(sizeof(int)); + return 0; } \ No newline at end of file