Commit 5364ae41 by Tomasz Blaszczak

Resize array in remove_from_array() and fix a crash

When an item is added to an array, then the array is realloc()ed (to size+1), and the item is copied (strdup()) to the array. Thus, when an item is removed from an array, allocated memory pointed by the item (not the item itself) should be freed, successive items should be left-shifted and the array realloc()ed again (size-1). Additional changes: - Initialize an array in list_all_containers(). Signed-off-by: 's avatarTomasz Blaszczak <tomasz.blaszczak@consult.red>
parent fe444ea6
...@@ -2262,7 +2262,7 @@ static inline int container_cmp(struct lxc_container **first, ...@@ -2262,7 +2262,7 @@ static inline int container_cmp(struct lxc_container **first,
static bool add_to_array(char ***names, char *cname, int pos) static bool add_to_array(char ***names, char *cname, int pos)
{ {
char **newnames = realloc(*names, (pos+1) * sizeof(char *)); char **newnames = (char**)realloc(*names, (pos+1) * sizeof(char *));
if (!newnames) { if (!newnames) {
ERROR("Out of memory"); ERROR("Out of memory");
return false; return false;
...@@ -2270,10 +2270,8 @@ static bool add_to_array(char ***names, char *cname, int pos) ...@@ -2270,10 +2270,8 @@ static bool add_to_array(char ***names, char *cname, int pos)
*names = newnames; *names = newnames;
newnames[pos] = strdup(cname); newnames[pos] = strdup(cname);
if (!newnames[pos]) { if (!newnames[pos])
*names = (char**)realloc(*names, (pos) * sizeof(char *));
return false; return false;
}
/* Sort the array as we will use binary search on it. */ /* Sort the array as we will use binary search on it. */
qsort(newnames, pos + 1, sizeof(char *), qsort(newnames, pos + 1, sizeof(char *),
...@@ -2322,12 +2320,16 @@ static bool remove_from_array(char ***names, char *cname, int size) ...@@ -2322,12 +2320,16 @@ static bool remove_from_array(char ***names, char *cname, int size)
{ {
char **result = get_from_array(names, cname, size); char **result = get_from_array(names, cname, size);
if (result != NULL) { if (result != NULL) {
int i; size_t i = result - *names;
for (i = 0; (*names)[i] != *result && i < size; i++) {
}
free(*result); free(*result);
memmove(*names+i, *names+i+1, (size-i-1) * sizeof(char*)); memmove(*names+i, *names+i+1, (size-i-1) * sizeof(char*));
*names = (char**)realloc(*names, (size-1) * sizeof(char *)); char **newnames = (char**)realloc(*names, (size-1) * sizeof(char *));
if (!newnames) {
ERROR("Out of memory");
return false;
}
*names = newnames;
return true; return true;
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment