]> git.dujemihanovic.xyz Git - u-boot.git/commitdiff
sandbox: avoid memory leak in os_dirent_ls
authorHeinrich Schuchardt <xypron.glpk@gmx.de>
Thu, 21 Sep 2017 10:56:07 +0000 (12:56 +0200)
committerSimon Glass <sjg@chromium.org>
Mon, 9 Oct 2017 02:41:09 +0000 (20:41 -0600)
Realloc does not free the old memory area if it fails.

Identified by cppcheck.

Signed-off-by: Heinrich Schuchardt <xypron.glpk@gmx.de>
Reviewed-by: Simon Glass <sjg@chromium.org>
arch/sandbox/cpu/os.c

index 22d6aab5348130d2f5dc1b7778051a2facff075a..c524957b6c531afcc1d5d68d0e52c09cadb7a0ba 100644 (file)
@@ -319,6 +319,7 @@ int os_dirent_ls(const char *dirname, struct os_dirent_node **headp)
        DIR *dir;
        int ret;
        char *fname;
+       char *old_fname;
        int len;
        int dirlen;
 
@@ -344,16 +345,23 @@ int os_dirent_ls(const char *dirname, struct os_dirent_node **headp)
                        break;
                }
                next = malloc(sizeof(*node) + strlen(entry->d_name) + 1);
-               if (dirlen + strlen(entry->d_name) > len) {
-                       len = dirlen + strlen(entry->d_name);
-                       fname = realloc(fname, len);
-               }
-               if (!next || !fname) {
-                       free(next);
+               if (!next) {
                        os_dirent_free(head);
                        ret = -ENOMEM;
                        goto done;
                }
+               if (dirlen + strlen(entry->d_name) > len) {
+                       len = dirlen + strlen(entry->d_name);
+                       old_fname = fname;
+                       fname = realloc(fname, len);
+                       if (!fname) {
+                               free(old_fname);
+                               free(next);
+                               os_dirent_free(head);
+                               ret = -ENOMEM;
+                               goto done;
+                       }
+               }
                next->next = NULL;
                strcpy(next->name, entry->d_name);
                switch (entry->d_type) {