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

pull/6/head
GreekStapler 2023-01-31 20:41:05 +00:00
parent bcae64e023
commit 9211bc3351
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);