aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorThomas Vanbesien <tvanbesi@proton.me>2026-02-27 12:02:16 +0100
committerThomas Vanbesien <tvanbesi@proton.me>2026-02-27 12:02:16 +0100
commit25d16ff06c2551ed090c2847efdc819303e577f3 (patch)
tree6823f9d9afa332a91de19a27722d53f12a12f15e /src
parentb8de4f339318dc245b073f05e186c4b2b1e8e758 (diff)
downloadmalloc-25d16ff06c2551ed090c2847efdc819303e577f3.tar.gz
malloc-25d16ff06c2551ed090c2847efdc819303e577f3.zip
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.
Diffstat (limited to 'src')
-rw-r--r--src/realloc.c36
1 files changed, 31 insertions, 5 deletions
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);
}