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

"Jerome Marchand" <[email protected]>
Newsgroups org.kernel.vger.linux-trace-devel
Message-ID <[email protected]>
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 <[email protected]>
---
 src/tracefs-events.c | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)

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);
-- 
2.44.0
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.