libsessiond: fix a memory leak in the `query_dir_via_readdir` routine 28/285428/2
authorAdam Michalski <a.michalski2@partner.samsung.com>
Mon, 12 Dec 2022 13:57:35 +0000 (14:57 +0100)
committerMichal Bloch <m.bloch@samsung.com>
Mon, 12 Dec 2022 17:14:33 +0000 (18:14 +0100)
`subsession_get_user_list` has non-obvious semantics. When it is called
with the `user_list` parameter set to NULL, the caller is only
interested in the number of subsessions associated with the
`session_uid` user. In this case it is unnecessary and undesirable to
allocate memory for the user list, as it leads to a memory leak, since
we are not passing the pointer to the caller.

Change-Id: Iac30507f6e3ac826ac66254b9404edbf17d95230

src/library/src/lib.c

index 4e3eda7c36fa33915834d1a3bbdc2f33510e7367..be981087ec1259dd4e952eb84ef086ab7765b040 100644 (file)
@@ -939,18 +939,19 @@ static int query_dir_via_readdir(DIR *const dir_ptr, subsession_user_t **const u
                        if (!error_on_bad_user_id(entry_ptr->d_name))
                                ++elems;
 
-       *user_count = 1;
-
-       subsession_user_t *const list = calloc(elems, sizeof *list);
-       if (list == NULL)
-               return SUBSESSION_ERROR_OUT_OF_MEMORY;
        if (user_list != NULL) {
+               subsession_user_t *const list = calloc(elems, sizeof *list);
+               if (list == NULL)
+                       return SUBSESSION_ERROR_OUT_OF_MEMORY;
+
                *user_list = list;
-               subsession_user_copy((*user_list)[0], SUBSESSION_INITIAL_SID);
+               subsession_user_copy(list[0], SUBSESSION_INITIAL_SID);
        }
 
-       if (elems == 1)
+       if (elems == 1) {
+               *user_count = 1;
                return SUBSESSION_ERROR_NONE;
+       }
 
        rewinddir(dir_ptr);