From: Maks Mishin <maks.mishi...@gmail.com> 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.
Signed-off-by: Maks Mishin <maks.mishi...@gmail.com> Signed-off-by: Anton Moryakov <ant.v.morya...@gmail.com> --- tools/zynqmpbif.c | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/tools/zynqmpbif.c b/tools/zynqmpbif.c index 82ce0ac1a52..33c68eac9f3 100644 --- a/tools/zynqmpbif.c +++ b/tools/zynqmpbif.c @@ -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; -- 2.30.2