fix: Took a very long time finding a very annyoing bug because realloc is the devil.

package
GreekStapler 2023-01-25 17:24:03 +01:00
parent edca243331
commit 01688fd546
2 changed files with 8 additions and 8 deletions

View File

@ -5,6 +5,11 @@
#include <string.h>
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);

View File

@ -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,7 +15,8 @@ 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;
}