From 5be56d0fcf604cb99f4b110f87ec00573f5fe715 Mon Sep 17 00:00:00 2001 From: Michael Tremer Date: Sat, 4 Jan 2025 15:48:32 +0000 Subject: [PATCH] strings: Copy strings a lot when appending to an array The static analyzer thinks we are leaking memory, and so we have to make things a little bit easier for it. Signed-off-by: Michael Tremer --- src/pakfire/string.c | 32 +++++++++++++------------------- 1 file changed, 13 insertions(+), 19 deletions(-) diff --git a/src/pakfire/string.c b/src/pakfire/string.c index 7e59d09af..19fe4aa85 100644 --- a/src/pakfire/string.c +++ b/src/pakfire/string.c @@ -404,42 +404,37 @@ void pakfire_strings_free(char** array) { free(array); } -static int __pakfire_strings_append(char*** array, char* s) { +int pakfire_strings_append(char*** array, const char* s) { if (!array) return -EINVAL; + // Copy the string + char* p = strdup(s); + if (!p) + goto ERROR; + // Fetch the length size_t length = pakfire_strings_length(*array); // Resize the array *array = reallocarray(*array, length + 2, sizeof(**array)); if (!*array) - return -errno; + goto ERROR; // Store the string - (*array)[length++] = s; + (*array)[length++] = p; // Terminate the array (*array)[length] = NULL; // Return the total length of the array return length; -} - -int pakfire_strings_append(char*** array, const char* s) { - int r; - // Copy the string - char* p = strdup(s); - if (!p) - return -errno; - - // Append it to the array - r = __pakfire_strings_append(array, p); - if (r < 0) +ERROR: + if (p) free(p); - return r; + return -errno; } int pakfire_strings_appendf(char*** array, const char* format, ...) { @@ -457,9 +452,8 @@ int pakfire_strings_appendf(char*** array, const char* format, ...) { return -errno; // Append it to the array - r = __pakfire_strings_append(array, p); - if (r < 0) - free(p); + r = pakfire_strings_append(array, p); + free(p); return r; } -- 2.47.3