From 25d16ff06c2551ed090c2847efdc819303e577f3 Mon Sep 17 00:00:00 2001 From: Thomas Vanbesien Date: Fri, 27 Feb 2026 12:02:16 +0100 Subject: Implement realloc and add realloc rounds to random test realloc returns the same pointer if the chunk is large enough, otherwise malloc + memcpy + free. The random test now verifies data integrity after resizing across all three categories. --- src/realloc.c | 36 +++++++++++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 5 deletions(-) (limited to 'src/realloc.c') diff --git a/src/realloc.c b/src/realloc.c index c0bbfed..3cc92f1 100644 --- a/src/realloc.c +++ b/src/realloc.c @@ -1,16 +1,42 @@ /** * @file realloc.c - * @brief Stub implementation of realloc. + * @brief realloc implementation. */ #include "libft.h" #include "malloc.h" +#include "malloc_internal.h" + +static t_chunk * +_s_ptr_to_chunk (void *ptr) +{ + return ((t_chunk *)((char *)ptr - ALIGN (sizeof (t_chunk)))); +} void * realloc (void *ptr, size_t size) { - (void)ptr; - (void)size; - ft_putendl_fd ("REALLOC", 1); - return (NULL); + t_chunk *chunk; + void *new_ptr; + size_t copy_size; + + if (!ptr) + return (malloc (size)); + if (size == 0) + { + free (ptr); + return (NULL); + } + chunk = _s_ptr_to_chunk (ptr); + if (chunk->size >= ALIGN (size)) + return (ptr); + new_ptr = malloc (size); + if (!new_ptr) + return (NULL); + copy_size = chunk->size; + if (copy_size > size) + copy_size = size; + ft_memcpy (new_ptr, ptr, copy_size); + free (ptr); + return (new_ptr); } -- cgit v1.2.3