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 <alx@kernel.org>
This commit is contained in:
committed by
Serge Hallyn
parent
2f4b5f5d80
commit
512deecca5
+4
-6
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user