[PATCH] perf metricgroup: Fix memory leak of metric_name in metricgroup__copy_metric_events

From: Wang Yan

Date: Thu Jul 09 2026 - 23:24:11 EST


In metricgroup__copy_metric_events(), new_expr->metric_name is allocated
via strdup() but is not freed in all error paths, leading to a memory
leak when subsequent allocations or evsel lookups fail.

Add the missing zfree() calls:

- On strdup() failure, free the already allocated new_expr.
- On metric_refs allocation failure, free metric_name before freeing
new_expr.
- On metric_events allocation failure, free metric_name in addition
to existing freeing of metric_refs and new_expr.
- On evsel lookup failure, free metric_name along with the other
resources already freed.

Fixes: b214ba8c4275 ("perf tools: Copy metric events properly when expand cgroups")
Signed-off-by: Wang Yan <wangyan01@xxxxxxxxxx>
---
tools/perf/util/metricgroup.c | 7 ++++++-
1 file changed, 6 insertions(+), 1 deletion(-)

diff --git a/tools/perf/util/metricgroup.c b/tools/perf/util/metricgroup.c
index 69bfa2a723b2..96dd780a5601 100644
--- a/tools/perf/util/metricgroup.c
+++ b/tools/perf/util/metricgroup.c
@@ -1693,8 +1693,10 @@ int metricgroup__copy_metric_events(struct evlist *evlist, struct cgroup *cgrp,
new_expr->metric_expr = old_expr->metric_expr;
new_expr->metric_threshold = old_expr->metric_threshold;
new_expr->metric_name = strdup(old_expr->metric_name);
- if (!new_expr->metric_name)
+ if (!new_expr->metric_name) {
+ free(new_expr);
return -ENOMEM;
+ }

new_expr->metric_unit = old_expr->metric_unit;
new_expr->runtime = old_expr->runtime;
@@ -1707,6 +1709,7 @@ int metricgroup__copy_metric_events(struct evlist *evlist, struct cgroup *cgrp,
alloc_size = sizeof(*new_expr->metric_refs);
new_expr->metric_refs = calloc(nr + 1, alloc_size);
if (!new_expr->metric_refs) {
+ zfree(&new_expr->metric_name);
free(new_expr);
return -ENOMEM;
}
@@ -1724,6 +1727,7 @@ int metricgroup__copy_metric_events(struct evlist *evlist, struct cgroup *cgrp,
new_expr->metric_events = calloc(nr + 1, alloc_size);
if (!new_expr->metric_events) {
zfree(&new_expr->metric_refs);
+ zfree(&new_expr->metric_name);
free(new_expr);
return -ENOMEM;
}
@@ -1735,6 +1739,7 @@ int metricgroup__copy_metric_events(struct evlist *evlist, struct cgroup *cgrp,
if (evsel == NULL) {
zfree(&new_expr->metric_events);
zfree(&new_expr->metric_refs);
+ zfree(&new_expr->metric_name);
free(new_expr);
return -EINVAL;
}
--
2.25.1