diff mbox series

[1/8] trace-cmd lib: Prevent a memory leak in handle_options()

Message ID 20241029080117.625177-2-jmarchan@redhat.com (mailing list archive)
State Accepted
Commit 5e8b3c1621296314cdf37adf40fc557203f18e9c
Headers show
Series trace-cmd: fix misc issues found by static analysis | expand

Commit Message

Jerome Marchand Oct. 29, 2024, 8:01 a.m. UTC
Buf isn't always fred in the error path. Instead of freing buf at the
end of the loop, free it in the exit path and before reallocating it.

Fixes a RESOURCE_LEAK error (CWE-772)

Signed-off-by: Jerome Marchand <jmarchan@redhat.com>
---
 lib/trace-cmd/trace-input.c | 7 +++----
 1 file changed, 3 insertions(+), 4 deletions(-)
diff mbox series

Patch

diff --git a/lib/trace-cmd/trace-input.c b/lib/trace-cmd/trace-input.c
index 8b6e3d0c..ad662fc6 100644
--- a/lib/trace-cmd/trace-input.c
+++ b/lib/trace-cmd/trace-input.c
@@ -4006,7 +4006,7 @@  static int handle_options(struct tracecmd_input *handle)
 	char *cpustats = NULL;
 	struct hook_list *hook;
 	bool compress = false;
-	char *buf;
+	char *buf = NULL;
 	int cpus;
 	int ret;
 
@@ -4036,6 +4036,7 @@  static int handle_options(struct tracecmd_input *handle)
 		ret = read4(handle, &size);
 		if (ret)
 			goto out;
+		free(buf);
 		buf = malloc(size);
 		if (!buf) {
 			ret = -ENOMEM;
@@ -4189,14 +4190,12 @@  static int handle_options(struct tracecmd_input *handle)
 			tracecmd_warning("unknown option %d", option);
 			break;
 		}
-
-		free(buf);
-
 	}
 
 	ret = 0;
 
 out:
+	free(buf);
 	if (compress)
 		in_uncompress_reset(handle);
 	return ret;