From 512deecca5f63410943b99c48f32836808fb0c3c Mon Sep 17 00:00:00 2001 From: Alejandro Colomar Date: Wed, 6 Nov 2024 01:20:17 +0100 Subject: [PATCH] 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 --- lib/gshadow.c | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) 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; -- 2.47.3