Thread (3 messages) flat view 3 messages, 2 authors, 2021-03-03
STALE2026d

[PATCH] bcache-tools: check whether allocating memory fails in tree()

From: Zhiqiang Liu <hidden>
Date: 2021-02-27 02:37:49
Subsystem: the rest · Maintainer: Linus Torvalds

In tree(), we do not check whether malloc() returns NULL,
it may cause potential Null pointer dereference problem.
In addition, when we fail to list devices, we should free(out)
before return.

Signed-off-by: ZhiqiangLiu <redacted>
---
 bcache.c | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)
diff --git a/bcache.c b/bcache.c
index 044d401..1c4cef9 100644
--- a/bcache.c
+++ b/bcache.c
@@ -174,7 +174,7 @@ void replace_line(char **dest, const char *from, const char *to)

 int tree(void)
 {
-	char *out = (char *)malloc(4096);
+	char *out;
 	const char *begin = ".\n";
 	const char *middle = "├─";
 	const char *tail = "└─";
@@ -184,8 +184,15 @@ int tree(void)
 	INIT_LIST_HEAD(&head);
 	int ret;

+	out = (char *)malloc(4096);
+	if (out == NULL) {
+		fprintf(stderr, "Error: fail to allocate memory buffer\n");
+		return 1;
+	}
+
 	ret = list_bdevs(&head);
 	if (ret != 0) {
+		free(out);
 		fprintf(stderr, "Failed to list devices\n");
 		return ret;
 	}
-- 
2.30.0

Keyboard shortcuts
hback out one level
jnext message in thread
kprevious message in thread
ldrill in
Escclose help / fold thread tree
?toggle this help