src/string.c

changeset 1040
1ecf4dbbc60c
parent 1001
5c9ec5a0a4ef
child 1041
508dc8b32a17
--- a/src/string.c	Fri Dec 20 21:25:33 2024 +0100
+++ b/src/string.c	Sat Dec 21 21:03:28 2024 +0100
@@ -92,6 +92,7 @@
     size_t size = 0;
     for (size_t i = 0; i < count; i++) {
         cxstring str = va_arg(ap, cxstring);
+        if (size > SIZE_MAX - str.length) errno = EOVERFLOW;
         size += str.length;
     }
     va_end(ap);
@@ -122,14 +123,25 @@
     va_start(ap, count);
 
     // get all args and overall length
+    bool overflow = false;
     size_t slen = str.length;
     for (size_t i = 0; i < count; i++) {
         cxstring s = va_arg (ap, cxstring);
         strings[i] = s;
+        if (slen > SIZE_MAX - str.length) overflow = true;
         slen += s.length;
     }
     va_end(ap);
 
+    // abort in case of overflow
+    if (overflow) {
+        errno = EOVERFLOW;
+        if (strings != strings_stack) {
+            free(strings);
+        }
+        return (cxmutstr) { NULL, 0 };
+    }
+
     // reallocate or create new string
     char *newstr;
     if (str.ptr == NULL) {
@@ -138,7 +150,9 @@
         newstr = cxRealloc(alloc, str.ptr, slen + 1);
     }
     if (newstr == NULL) {
-        free(strings);
+        if (strings != strings_stack) {
+            free(strings);
+        }
         return (cxmutstr) {NULL, 0};
     }
     str.ptr = newstr;

mercurial