]> git.ipfire.org Git - thirdparty/lxc.git/commitdiff
When an item is added to an array, then the array is realloc()ed (to size+1),
authorTomasz Blaszczak <tomasz.blaszczak@consult.red>
Wed, 23 Jun 2021 07:17:05 +0000 (09:17 +0200)
committerTomasz Blaszczak <tomasz.blaszczak@consult.red>
Wed, 23 Jun 2021 08:41:39 +0000 (10:41 +0200)
and the item is copied (strdup()) to the array.
Thus, when an item is removed from an array, memory allocated for that item
should be freed, successive items should be left-shifted and the array
realloc()ed again (size-1).

Additional changes:
- If strdup() fails in add_to_array(), then an array should be
  realloc()ed again to original size.
- Initialize an array in list_all_containers().

Signed-off-by: Tomasz Blaszczak <tomasz.blaszczak@consult.red>
src/lxc/lxccontainer.c

index 34149675ed607d0405843427459d80c8f848f2a5..b1be7e0ed5fb4f432981339da1e5416935422f52 100644 (file)
@@ -2270,8 +2270,10 @@ static bool add_to_array(char ***names, char *cname, int pos)
 
        *names = newnames;
        newnames[pos] = strdup(cname);
-       if (!newnames[pos])
+       if (!newnames[pos]) {
+               *names = (char**)realloc(*names, (pos) * sizeof(char *));
                return false;
+       }
 
        /* Sort the array as we will use binary search on it. */
        qsort(newnames, pos + 1, sizeof(char *),
@@ -2320,7 +2322,12 @@ static bool remove_from_array(char ***names, char *cname, int size)
 {
        char **result = get_from_array(names, cname, size);
        if (result != NULL) {
-               free(result);
+               int i;
+               for (i = 0; (*names)[i] != *result && i < size; i++) {
+               }
+               free(*result);
+               memmove(*names+i, *names+i+1, (size-i-1) * sizeof(char*));
+               *names = (char**)realloc(*names, (size-1) * sizeof(char *));
                return true;
        }
 
@@ -5659,7 +5666,7 @@ int list_all_containers(const char *lxcpath, char ***nret,
 {
        int i, ret, active_cnt, ct_cnt, ct_list_cnt;
        char **active_name;
-       char **ct_name;
+       char **ct_name = NULL;
        struct lxc_container **ct_list = NULL;
 
        ct_cnt = list_defined_containers(lxcpath, &ct_name, NULL);