From 31fc4e2989a154d96122f9416b63312d9115f93c Mon Sep 17 00:00:00 2001 From: GreekStapler Date: Wed, 25 Jan 2023 17:24:03 +0100 Subject: [PATCH] fix: Took a very long time finding a very annyoing bug because realloc is the devil. --- include/dynarray.h | 5 +++++ src/package/dynarray.c | 11 +++-------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/include/dynarray.h b/include/dynarray.h index e552ec4..2ab4022 100644 --- a/include/dynarray.h +++ b/include/dynarray.h @@ -5,6 +5,11 @@ #include typedef struct dyn_array DynArray; +struct dyn_array { + char **array; + size_t capacity; + size_t size; +}; DynArray *dynarray_init(size_t initial_capacity); void dynarray_add(DynArray *da, const char * s); diff --git a/src/package/dynarray.c b/src/package/dynarray.c index 480c08f..a78e7ff 100644 --- a/src/package/dynarray.c +++ b/src/package/dynarray.c @@ -1,11 +1,5 @@ #include "dynarray.h" -struct dyn_array { - char **array; - size_t size; - size_t capacity; -}; - DynArray *dynarray_init(size_t initial_capacity) { DynArray *da = malloc(sizeof(DynArray)); da->size = 0; @@ -21,10 +15,11 @@ void dynarray_add(DynArray *da, const char *s) { } // Double array size if it's full else if (da->size == da->capacity) { - da->array = realloc(da->array, da->capacity * 2); + // if the realloc fails, access to memory in da->array is lost + da->array = realloc(da->array, sizeof(char*) * da->capacity * 2); da->capacity *= 2; } - + da->array[da->size] = strdup(s); da->size++; }