]> git.ipfire.org Git - thirdparty/shadow.git/commitdiff
lib/addgrps.c: add_groups(): Reallocate at once
authorAlejandro Colomar <alx@kernel.org>
Thu, 14 Nov 2024 18:58:54 +0000 (19:58 +0100)
committerSerge Hallyn <serge@hallyn.com>
Fri, 24 Jan 2025 13:58:13 +0000 (07:58 -0600)
We can calculate an upper bound of the number of added groups by
counting the number of delimiters in the string (plus one for the
element after the last delimiter).  This avoids reallocating +1 in a
loop.

Reviewed-by: Serge Hallyn <serge@hallyn.com>
Signed-off-by: Alejandro Colomar <alx@kernel.org>
lib/addgrps.c

index 88a9710bca84f3433ec7a2fa1e1de9f171ddbf63..603197543ef9a9de19f5e3d6672be639f95a6c7f 100644 (file)
@@ -22,8 +22,7 @@
 #include "alloc/reallocf.h"
 #include "search/l/lsearch.h"
 #include "shadowlog.h"
-
-#ident "$Id$"
+#include "string/strchr/strchrscnt.h"
 
 
 /*
@@ -59,6 +58,10 @@ add_groups(const char *list)
        if (n0 == -1)
                goto free_gids;
 
+       grouplist = REALLOCF(grouplist, n0 + strchrscnt(list, ",:") + 1, GETGROUPS_T);
+       if (grouplist == NULL)
+               return -1;
+
        n = n0;
        p = buf;
        while (NULL != (g = strsep(&p, ",:"))) {
@@ -70,10 +73,6 @@ add_groups(const char *list)
                        continue;
                }
 
-               grouplist = REALLOCF(grouplist, n + 1, GETGROUPS_T);
-               if (grouplist == NULL)
-                       return -1;
-
                LSEARCH(&grp->gr_gid, grouplist, &n);
        }