fix ineffecient string list reallocation - fixes #637

Wed, 09 Apr 2025 21:47:07 +0200

author
Mike Becker <universe@uap-core.de>
date
Wed, 09 Apr 2025 21:47:07 +0200
changeset 81
54515e5d60f5
parent 80
55dc85743dd1
child 82
44b3332dfe03

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);
   }
--- 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;
 

mercurial