Wed, 09 Apr 2025 21:47:07 +0200
fix ineffecient string list reallocation - fixes #637
src/string_list.c | file | annotate | diff | comparison | revisions | |
src/string_list.h | file | annotate | diff | comparison | revisions |
--- a/src/string_list.c Tue Apr 08 19:10:52 2025 +0200 +++ b/src/string_list.c Wed Apr 09 21:47:07 2025 +0200 @@ -26,10 +26,13 @@ #include "string_list.h" +#include <assert.h> + string_list_t* new_string_list_t() { string_list_t* stringList = malloc(sizeof(string_list_t)); stringList->count = 0; - stringList->items = NULL; + stringList->capacity = 32; + stringList->items = calloc(sizeof(char*), stringList->capacity); return stringList; } @@ -48,13 +51,17 @@ */ void add_string(string_list_t* list, char* item) { if (list) { + if (list->count < list->capacity) { + list->items[list->count++] = item; + return; + } + size_t newCapacity = list->capacity * 2; char** reallocated_list = - realloc(list->items, sizeof(char*) * (list->count + 1)); - if (reallocated_list != NULL) { - list->items = reallocated_list; - list->items[list->count] = item; - list->count++; - } + realloc(list->items, sizeof(char*) * newCapacity); + assert(reallocated_list != NULL); + list->capacity = newCapacity; + list->items = reallocated_list; + list->items[list->count++] = item; } else { free(item); }