]> git.ipfire.org Git - thirdparty/shadow.git/commitdiff
lib/gshadow.c: build_list(): Allocate at once
authorAlejandro Colomar <alx@kernel.org>
Wed, 6 Nov 2024 00:20:17 +0000 (01:20 +0100)
committerSerge Hallyn <serge@hallyn.com>
Fri, 6 Dec 2024 03:20:59 +0000 (21:20 -0600)
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 <alx@kernel.org>
lib/gshadow.c

index 304c66c44eb3846d8fe51d4151adb87ae6b6cd04..983aa4c88706edef3c1d90674bf7a36b282a93f5 100644 (file)
 
 #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;