diff mbox series

[09/15] libtracefs: prevent a memory leak in open_cpu_files()

Message ID 20240606153830.2666120-10-jmarchan@redhat.com (mailing list archive)
State Accepted
Commit 8f2593fbbad2a549b854645acde7b11f5e02a924
Headers show
Series libtracefs: fix misc issues found by static analysis | expand

Commit Message

Jerome Marchand June 6, 2024, 3:38 p.m. UTC
In open_cpu_files(), if realloc() fails the latest allocated tcpu
isn't freed. Rearrange the loop to prevent that.

Signed-off-by: Jerome Marchand <jmarchan@redhat.com>
---
 src/tracefs-events.c | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)
diff mbox series

Patch

diff --git a/src/tracefs-events.c b/src/tracefs-events.c
index d65837e..88325e1 100644
--- a/src/tracefs-events.c
+++ b/src/tracefs-events.c
@@ -275,9 +275,12 @@  static int open_cpu_files(struct tracefs_instance *instance, cpu_set_t *cpus,
 			tcpu = tracefs_cpu_snapshot_open(instance, cpu, true);
 		else
 			tcpu = tracefs_cpu_open_mapped(instance, cpu, true);
+		if (!tcpu)
+			goto error;
+
 		tmp = realloc(*all_cpus, (i + 1) * sizeof(*tmp));
 		if (!tmp) {
-			i--;
+			tracefs_cpu_close(tcpu);
 			goto error;
 		}
 
@@ -285,9 +288,6 @@  static int open_cpu_files(struct tracefs_instance *instance, cpu_set_t *cpus,
 
 		memset(tmp + i, 0, sizeof(*tmp));
 
-		if (!tcpu)
-			goto error;
-
 		tmp[i].tcpu = tcpu;
 		tmp[i].cpu = cpu;
 		i++;
@@ -296,7 +296,7 @@  static int open_cpu_files(struct tracefs_instance *instance, cpu_set_t *cpus,
 	return 0;
  error:
 	tmp = *all_cpus;
-	for (; i >= 0; i--) {
+	for (i--; i >= 0; i--) {
 		tracefs_cpu_close(tmp[i].tcpu);
 	}
 	free(tmp);