fix: Initialise array pointers to 0 before performing check on them.

GreekStapler 2023-01-31 20:41:05 +00:00
parent 4cacb1534f
commit 307e7ba6e9
1 changed files with 6 additions and 0 deletions

View File

@ -12,12 +12,18 @@ void vieter_package_dynarray_add(vieter_package_dynarray *da, const char *s) {
// An empty vieter_package_dynarray does not have an allocated internal array yet
if (da->size == 0) {
da->array = malloc(sizeof(char*) * da->capacity);
// Initialise all char*'s to 0 so array[i] == NULL can be used to see if field is empty
memset(da->array, 0, sizeof(char*) * da->capacity);
}
// Double array size if it's full
else if (da->size == da->capacity) {
// 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;
// Same as the previous memset, but only for newly allocated pointers
memset(da->array + da->size, 0, sizeof(char*) * da->capacity / 2);
}
da->array[da->size] = strdup(s);