dump_systemstate-service: Fix possible memory leaks 66/294966/1 accepted/tizen_unified_dev accepted/tizen/unified/dev/20230726.115826
authorSung-hun Kim <sfoon.kim@samsung.com>
Thu, 29 Jun 2023 06:57:33 +0000 (15:57 +0900)
committerSung-hun Kim <sfoon.kim@samsung.com>
Thu, 29 Jun 2023 06:57:33 +0000 (15:57 +0900)
The `strdup` call uses `malloc` internally for allocating memory
area. Thus, the result of `strdup` should be freed in the
allocation failed cases.

Change-Id: I01a1f1653cd1ddbac5e89cdfb085e0d273414c6c
Signed-off-by: Sung-hun Kim <sfoon.kim@samsung.com>
src/dump_systemstate-service/dump_systemstate-service.c

index aa71c33..f9552f9 100644 (file)
@@ -94,23 +94,19 @@ char** split(const char *str, size_t *size)
 
                if (result_tmp == NULL) {
                        _E("Out of memory");
-                       if (result != NULL)
-                               free(result);
-                       result = NULL;
-
                        if (chunk_copy != NULL)
                                free(chunk_copy);
+                       if (result != NULL)
+                               goto result_free;
                        goto out;
                }
 
+               result = result_tmp;
                if (chunk_copy == NULL) {
                        _E("Out of memory");
-                       free(result_tmp);
-                       result = NULL;
-                       goto out;
+                       goto result_free;
                }
 
-               result = result_tmp;
                result[(*size)++] = chunk_copy;
                chunk = strtok_r(NULL, " ", &tmpptr);
        }
@@ -118,17 +114,22 @@ char** split(const char *str, size_t *size)
        char **result_tmp = realloc(result, (*size + 1) * sizeof(char *));
        if (result_tmp == NULL) {
                _E("Out of memory");
-               free(result);
-               result = NULL;
-               goto out;
+               goto result_free;
        }
 
        result = result_tmp;
        result[*size] = NULL;
-
 out:
        free(str_tmp);
        return result;
+
+result_free:
+       for (size_t i = 0; i < *size; i++)
+               free(result[i]);
+       *size = 0;
+       free(result);
+       free(str_tmp);
+       return NULL;
 }
 
 static void free_array(char **array)