From aaaa3d41a5379aae745d53fae5870ec8678a889e Mon Sep 17 00:00:00 2001 From: Alejandro Colomar Date: Thu, 14 Nov 2024 19:58:54 +0100 Subject: [PATCH] lib/addgrps.c: add_groups(): Reallocate at once 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 Signed-off-by: Alejandro Colomar --- lib/addgrps.c | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/lib/addgrps.c b/lib/addgrps.c index 88a9710bc..603197543 100644 --- a/lib/addgrps.c +++ b/lib/addgrps.c @@ -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); } -- 2.47.2