fix: Took a very long time finding a very annyoing bug because realloc is the devil.
parent
edca243331
commit
01688fd546
|
@ -5,6 +5,11 @@
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
|
|
||||||
typedef struct dyn_array DynArray;
|
typedef struct dyn_array DynArray;
|
||||||
|
struct dyn_array {
|
||||||
|
char **array;
|
||||||
|
size_t capacity;
|
||||||
|
size_t size;
|
||||||
|
};
|
||||||
|
|
||||||
DynArray *dynarray_init(size_t initial_capacity);
|
DynArray *dynarray_init(size_t initial_capacity);
|
||||||
void dynarray_add(DynArray *da, const char * s);
|
void dynarray_add(DynArray *da, const char * s);
|
||||||
|
|
|
@ -1,11 +1,5 @@
|
||||||
#include "dynarray.h"
|
#include "dynarray.h"
|
||||||
|
|
||||||
struct dyn_array {
|
|
||||||
char **array;
|
|
||||||
size_t size;
|
|
||||||
size_t capacity;
|
|
||||||
};
|
|
||||||
|
|
||||||
DynArray *dynarray_init(size_t initial_capacity) {
|
DynArray *dynarray_init(size_t initial_capacity) {
|
||||||
DynArray *da = malloc(sizeof(DynArray));
|
DynArray *da = malloc(sizeof(DynArray));
|
||||||
da->size = 0;
|
da->size = 0;
|
||||||
|
@ -21,7 +15,8 @@ void dynarray_add(DynArray *da, const char *s) {
|
||||||
}
|
}
|
||||||
// Double array size if it's full
|
// Double array size if it's full
|
||||||
else if (da->size == da->capacity) {
|
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->capacity *= 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue