[PATCH v1] erofs-utils: misc: Fix potential memory leak in realloc failure path

Sandeep Dhavale dhavale at google.com
Fri Jul 19 06:22:04 AEST 2024


As realloc returns NULL on failure, the original value will be
overwritten if it is used as lvalue. Fix this by using a temporary
variable to hold the return value and exit with -ENOMEM in case of
failure. This patch fixes 2 of the realloc blocks with similar fix.

Signed-off-by: Sandeep Dhavale <dhavale at google.com>
---
 fsck/main.c | 9 +++++++--
 lib/data.c  | 5 +++--
 2 files changed, 10 insertions(+), 4 deletions(-)

diff --git a/fsck/main.c b/fsck/main.c
index 8ec9486..75950b6 100644
--- a/fsck/main.c
+++ b/fsck/main.c
@@ -508,8 +508,13 @@ static int erofs_verify_inode_data(struct erofs_inode *inode, int outfd)
 		if (compressed) {
 			if (map.m_llen > buffer_size) {
 				buffer_size = map.m_llen;
-				buffer = realloc(buffer, buffer_size);
-				BUG_ON(!buffer);
+				char *newbuffer = realloc(buffer, buffer_size);
+
+				if (!newbuffer) {
+					ret = -ENOMEM;
+					goto out;
+				}
+				buffer = newbuffer;
 			}
 			ret = z_erofs_read_one_data(inode, &map, raw, buffer,
 						    0, map.m_llen, false);
diff --git a/lib/data.c b/lib/data.c
index a8402ed..0fc013e 100644
--- a/lib/data.c
+++ b/lib/data.c
@@ -338,11 +338,12 @@ static int z_erofs_read_data(struct erofs_inode *inode, char *buffer,
 
 		if (map.m_plen > bufsize) {
 			bufsize = map.m_plen;
-			raw = realloc(raw, bufsize);
-			if (!raw) {
+			char *newraw = realloc(raw, bufsize);
+			if (!newraw) {
 				ret = -ENOMEM;
 				break;
 			}
+			raw = newraw;
 		}
 
 		ret = z_erofs_read_one_data(inode, &map, raw,
-- 
2.45.2.1089.g2a221341d9-goog



More information about the Linux-erofs mailing list