From: Alejandro Colomar Date: Wed, 6 Nov 2024 00:20:17 +0000 (+0100) Subject: lib/gshadow.c: build_list(): Allocate at once X-Git-Tag: 4.17.0-rc1~2 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=512deecca5f63410943b99c48f32836808fb0c3c;p=thirdparty%2Fshadow.git lib/gshadow.c: build_list(): Allocate at once Instead of reallocating 1 more meber per iteration, calculate the total amount that we want by counting the number of commas (delimiters) in the string, plus one for the last element, plus one for the terminating NULL. This might result in overallocation of one element if the string is an empty string, or if there's a trailing comma; however, that's not an issue. We can afford overallocating one element in certain cases, and we get in exchange a much simpler function. Signed-off-by: Alejandro Colomar --- diff --git a/lib/gshadow.c b/lib/gshadow.c index 304c66c44..983aa4c88 100644 --- a/lib/gshadow.c +++ b/lib/gshadow.c @@ -20,9 +20,10 @@ #include "alloc/malloc.h" #include "alloc/realloc.h" -#include "alloc/x/xrealloc.h" +#include "alloc/x/xmalloc.h" #include "defines.h" #include "prototypes.h" +#include "string/strchr/strchrcnt.h" #include "string/strcmp/streq.h" #include "string/strtok/stpsep.h" @@ -39,15 +40,12 @@ build_list(char *s) char **l; size_t n; - l = NULL; + l = XMALLOC(strchrcnt(s, ',') + 2, char *); n = 0; - while (s != NULL && *s != '\0') { - l = XREALLOC(l, n + 1, char *); + while (s != NULL && *s != '\0') l[n++] = strsep(&s, ","); - } - l = XREALLOC(l, n + 1, char *); l[n] = NULL; return l;