diff mbox series

[U-Boot,1/1] sandbox: avoid memory leak in os_dirent_ls

Message ID 20170921105607.28785-1-xypron.glpk@gmx.de
State Accepted, archived
Commit 04d0da51578e12bd7c490aa70ed581ee5f9dcfea
Delegated to: Simon Glass
Headers show
Series [U-Boot,1/1] sandbox: avoid memory leak in os_dirent_ls | expand

Commit Message

Heinrich Schuchardt Sept. 21, 2017, 10:56 a.m. UTC
Realloc does not free the old memory area if it fails.

Identified by cppcheck.

Signed-off-by: Heinrich Schuchardt <xypron.glpk@gmx.de>
---
 arch/sandbox/cpu/os.c | 20 ++++++++++++++------
 1 file changed, 14 insertions(+), 6 deletions(-)

Comments

Simon Glass Sept. 25, 2017, 2:13 a.m. UTC | #1
On 21 September 2017 at 04:56, Heinrich Schuchardt <xypron.glpk@gmx.de> wrote:
> Realloc does not free the old memory area if it fails.
>
> Identified by cppcheck.
>
> Signed-off-by: Heinrich Schuchardt <xypron.glpk@gmx.de>
> ---
>  arch/sandbox/cpu/os.c | 20 ++++++++++++++------
>  1 file changed, 14 insertions(+), 6 deletions(-)

Reviewed-by: Simon Glass <sjg@chromium.org>
Simon Glass Sept. 29, 2017, 9 p.m. UTC | #2
On 21 September 2017 at 04:56, Heinrich Schuchardt <xypron.glpk@gmx.de> wrote:
> Realloc does not free the old memory area if it fails.
>
> Identified by cppcheck.
>
> Signed-off-by: Heinrich Schuchardt <xypron.glpk@gmx.de>
> ---
>  arch/sandbox/cpu/os.c | 20 ++++++++++++++------
>  1 file changed, 14 insertions(+), 6 deletions(-)

Reviewed-by: Simon Glass <sjg@chromium.org>

Applied to u-boot-dm thanks!
diff mbox series

Patch

diff --git a/arch/sandbox/cpu/os.c b/arch/sandbox/cpu/os.c
index 22d6aab534..c524957b6c 100644
--- a/arch/sandbox/cpu/os.c
+++ b/arch/sandbox/cpu/os.c
@@ -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) {