tools: Fix memory and file descriptor leaks in read_full_file()
PATCH 1/1 tools: Fix memory and file descriptor leaks in read_full_file()
From: Maks Mishin <[email protected]>
Fixes potential memory and file descriptor leaks in the read_full_file() function. If malloc succeeds but read() fails, the buffer was not freed, and the file descriptor was not closed. This patch ensures both resources are properly released using a common exit point.
--- tools/zynqmpbif.c | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-)
tools/zynqmpbif.c +9 -5
@@ -205,7 +205,8 @@ static const struct bif_flags bif_flags[] = {static char *read_full_file (const char *filename,size_t *size) { -char *buf, *bufp; +char *buf =NULL , *bufp;struct stat sbuf;int len =0 , r, fd;
@@ -214,24 +215,29 @@ static char *read_full_file(const char *filename, size_t *size)return NULL ;if (fstat (fd, &sbuf) <0 ) -return NULL ; + goto out;if (size) *size = sbuf.st_size; buf =malloc (sbuf.st_size);if (!buf) -return NULL ; + goto out; bufp = buf;while (len < sbuf.st_size) { r =read (fd, bufp, sbuf.st_size - len); -if (r <0 ) -return NULL ; +if (r <0 ) { +free (buf); + buf =NULL ; + goto out; + } len += r; bufp += r; } +out:close (fd);return buf;
Signature · 1 line
2.30.2
Quoted 7 lines · On Fri, Apr 18, 2025 at 08:19:47PM +0300, [email protected] wrote:
From: Maks Mishin <[email protected]>
Fixes potential memory and file descriptor leaks in the
read_full_file()function. If malloc succeeds butread()fails, the buffer was not freed, and the file descriptor was not closed. This patch ensures both resources are properly released using a common exit point.
Quoted 5 lines
Signed-off-by Maks Mishin <[email protected]>Signed-off-by Anton Moryakov <[email protected]>--- tools/zynqmpbif.c | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-)
Please note that this patch is malformed:
patch: **** malformed patch at line 125: @@ -214,24 +215,29 @@ static char *read_full_file(const char *filename, size_t *size) as it looks like you're hand-editing the patches.
Signature · 1 line
Tom