src/string.c

changeset 1001
5c9ec5a0a4ef
parent 985
68754c7de906
--- a/src/string.c	Thu Dec 05 01:54:12 2024 +0100
+++ b/src/string.c	Sat Dec 07 23:59:54 2024 +0100
@@ -107,8 +107,16 @@
 ) {
     if (count == 0) return str;
 
-    cxstring *strings = calloc(count, sizeof(cxstring));
-    if (!strings) abort();
+    cxstring strings_stack[8];
+    cxstring *strings;
+    if (count > 8) {
+        strings = calloc(count, sizeof(cxstring));
+        if (strings == NULL) {
+            return (cxmutstr) {NULL, 0};
+        }
+    } else {
+        strings = strings_stack;
+    }
 
     va_list ap;
     va_start(ap, count);
@@ -123,12 +131,17 @@
     va_end(ap);
 
     // reallocate or create new string
+    char *newstr;
     if (str.ptr == NULL) {
-        str.ptr = cxMalloc(alloc, slen + 1);
+        newstr = cxMalloc(alloc, slen + 1);
     } else {
-        str.ptr = cxRealloc(alloc, str.ptr, slen + 1);
+        newstr = cxRealloc(alloc, str.ptr, slen + 1);
     }
-    if (str.ptr == NULL) abort();
+    if (newstr == NULL) {
+        free(strings);
+        return (cxmutstr) {NULL, 0};
+    }
+    str.ptr = newstr;
 
     // concatenate strings
     size_t pos = str.length;
@@ -143,7 +156,9 @@
     str.ptr[str.length] = '\0';
 
     // free temporary array
-    free(strings);
+    if (strings != strings_stack) {
+        free(strings);
+    }
 
     return str;
 }

mercurial