Skip to content

Commit 378deaa

Browse files
lib/list.c: realloc(3) to prevent memory leaks
Each call to add_list() that resulted in adding a group to the list was leaking the old list. There's no need to allocate a fresh list. Otherwise, it would be incorrect to return the original pointer in some cases, which we already did. Signed-off-by: Alejandro Colomar <[email protected]>
1 parent e78742e commit 378deaa

File tree

1 file changed

+5
-26
lines changed

1 file changed

+5
-26
lines changed

lib/list.c

Lines changed: 5 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
#include <assert.h>
1414

1515
#include "alloc/malloc.h"
16+
#include "alloc/realloc.h"
1617
#include "prototypes.h"
1718
#include "defines.h"
1819
#include "string/strchr/strchrcnt.h"
@@ -23,16 +24,11 @@
2324

2425
/*
2526
* add_list - add a member to a list of group members
26-
*
27-
* the array of member names is searched for the new member
28-
* name, and if not present it is added to a freshly allocated
29-
* list of users.
3027
*/
3128
/*@only@*/char **
3229
add_list(/*@returned@*/ /*@only@*/char **list, const char *member)
3330
{
3431
int i;
35-
char **tmp;
3632

3733
assert (NULL != member);
3834
assert (NULL != list);
@@ -41,34 +37,17 @@ add_list(/*@returned@*/ /*@only@*/char **list, const char *member)
4137
* Scan the list for the new name. Return the original list
4238
* pointer if it is present.
4339
*/
44-
4540
for (i = 0; list[i] != NULL; i++) {
4641
if (streq(list[i], member)) {
4742
return list;
4843
}
4944
}
5045

51-
/*
52-
* Allocate a new list pointer large enough to hold all the
53-
* old entries, and the new entries as well.
54-
*/
46+
list = xrealloc_T(list, i + 2, char *);
47+
list[i] = xstrdup(member);
48+
list[i+1] = NULL;
5549

56-
tmp = xmalloc_T(i + 2, char *);
57-
58-
/*
59-
* Copy the original list to the new list, then append the
60-
* new member and NULL terminate the result. This new list
61-
* is returned to the invoker.
62-
*/
63-
64-
for (i = 0; list[i] != NULL; i++) {
65-
tmp[i] = list[i];
66-
}
67-
68-
tmp[i] = xstrdup (member);
69-
tmp[i+1] = NULL;
70-
71-
return tmp;
50+
return list;
7251
}
7352

7453
/*

0 commit comments

Comments
 (0)