From f9a9720d3d34cf213a5393cdfdac989bed913e1a Mon Sep 17 00:00:00 2001 From: Danny Holman Date: Mon, 7 Oct 2024 13:35:00 -0500 Subject: core: alloc: fix a bug in realloc Fix a bug in realloc that wouldn't copy the data from the original pointer. The new implementation now copies the data and marks the old block as free, as well as returning a new block if the ptr argument is NULL. Signed-off-by: Danny Holman --- core/alloc.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/core/alloc.c b/core/alloc.c index 88ebb8f..a9f335c 100644 --- a/core/alloc.c +++ b/core/alloc.c @@ -1,6 +1,7 @@ #include #include #include +#include // TODO: implement block coalescing so we can reuse freed blocks @@ -69,12 +70,13 @@ void* rune_calloc(size_t nmemb, size_t sz) { void* rune_realloc(void *ptr, size_t sz) { if (ptr == NULL || sz == 0) - return NULL; + return rune_alloc(sz); struct mem_block *block = _find_block(ptr); - if (block == NULL) - return rune_alloc(sz); - return block->ptr; + void *new_ptr = rune_alloc(sz); + memcpy(new_ptr, ptr, block->sz); + block->free = 1; + return new_ptr; } void rune_free(void *ptr) { -- cgit v1.2.3