# HG changeset patch # User Mike Becker # Date 1744228027 -7200 # Node ID 54515e5d60f5b6915caab23f797c307bf49218a8 # Parent 55dc85743dd1f0479ee5d04afdd544eda4b13511 fix ineffecient string list reallocation - fixes #637 diff -r 55dc85743dd1 -r 54515e5d60f5 src/string_list.c --- 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 + 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); } diff -r 55dc85743dd1 -r 54515e5d60f5 src/string_list.h --- a/src/string_list.h Tue Apr 08 19:10:52 2025 +0200 +++ b/src/string_list.h Wed Apr 09 21:47:07 2025 +0200 @@ -31,6 +31,7 @@ typedef struct string_list_s { size_t count; + size_t capacity; char** items; } string_list_t;