From c0da3fdefe63f259ae0807df503c1cc5b3318d6c Mon Sep 17 00:00:00 2001 From: karutoh Date: Thu, 8 Feb 2024 17:42:03 -0800 Subject: [PATCH] Added ralloc function. --- main.c | 36 ++++++++++++++++++++++++++++++------ 1 file changed, 30 insertions(+), 6 deletions(-) diff --git a/main.c b/main.c index 753b5bc..9510dc7 100644 --- a/main.c +++ b/main.c @@ -52,6 +52,10 @@ struct block* find_first(size_t s) return current; } +/// Fragments an existing free memory block into the given size. +/// @param [in] in The memory block to fragment. +/// @param [in] s The size of the new memory block. +/// @returns The new memory block. struct block* fragment_block(struct block* in, size_t s) { size_t totalSize = BLOCK_SIZE + s; @@ -75,19 +79,19 @@ void* malloc(size_t size) { struct block* b; - size_t alignedSize = ALIGN4(size); + size = ALIGN4(size); if (first) { - b = find_first(alignedSize); + b = find_first(size); if (!b) - b = extend_heap(alignedSize); - else if (b->size > BLOCK_SIZE + alignedSize) - b = fragment_block(b, alignedSize); + b = extend_heap(size); + else if (b->size > BLOCK_SIZE + size) + b = fragment_block(b, size); } else { - b = extend_heap(alignedSize); + b = extend_heap(size); if (!b) return NULL; @@ -97,6 +101,26 @@ void* malloc(size_t size) return b + 1; } +void* realloc(void* ptr, size_t new_size) +{ + if (!ptr) + return malloc(new_size); + + if (!new_size) + return NULL; + + struct block* b = (struct block*)ptr - 1; + if (b->free) + return NULL; + + if (b->size == new_size) + return ptr; + else if (b->size > BLOCK_SIZE + new_size) + return fragment_block(b, new_size) + 1; + + return NULL; +} + /// 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.