tools/testing/selftests/cgroup/lib/cgroup_util.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-)
Add NULL checks after malloc() in three helper functions to prevent
NULL pointer dereference on memory allocation failure.
- cg_name()
- cg_name_indexed()
- cg_control()
These functions allocate memory with malloc() but previously called
snprintf() unconditionally, which would trigger undefined behavior
if allocation fails.
Signed-off-by: Hongfu Li <lihongfu@kylinos.cn>
---
tools/testing/selftests/cgroup/lib/cgroup_util.c | 9 ++++++---
1 file changed, 6 insertions(+), 3 deletions(-)
diff --git a/tools/testing/selftests/cgroup/lib/cgroup_util.c b/tools/testing/selftests/cgroup/lib/cgroup_util.c
index 6a7295347e90..0c5e6d4bbc3a 100644
--- a/tools/testing/selftests/cgroup/lib/cgroup_util.c
+++ b/tools/testing/selftests/cgroup/lib/cgroup_util.c
@@ -59,7 +59,8 @@ char *cg_name(const char *root, const char *name)
size_t len = strlen(root) + strlen(name) + 2;
char *ret = malloc(len);
- snprintf(ret, len, "%s/%s", root, name);
+ if (ret)
+ snprintf(ret, len, "%s/%s", root, name);
return ret;
}
@@ -69,7 +70,8 @@ char *cg_name_indexed(const char *root, const char *name, int index)
size_t len = strlen(root) + strlen(name) + 10;
char *ret = malloc(len);
- snprintf(ret, len, "%s/%s_%d", root, name, index);
+ if (ret)
+ snprintf(ret, len, "%s/%s_%d", root, name, index);
return ret;
}
@@ -79,7 +81,8 @@ char *cg_control(const char *cgroup, const char *control)
size_t len = strlen(cgroup) + strlen(control) + 2;
char *ret = malloc(len);
- snprintf(ret, len, "%s/%s", cgroup, control);
+ if (ret)
+ snprintf(ret, len, "%s/%s", cgroup, control);
return ret;
}
--
2.25.1
On Mon, May 11, 2026 at 02:08:53PM +0800, Hongfu Li wrote: > Add NULL checks after malloc() in three helper functions to prevent > NULL pointer dereference on memory allocation failure. > - cg_name() > - cg_name_indexed() > - cg_control() > > These functions allocate memory with malloc() but previously called > snprintf() unconditionally, which would trigger undefined behavior > if allocation fails. > > Signed-off-by: Hongfu Li <lihongfu@kylinos.cn> > --- Reviewed-by: Vishal Moola <vishal.moola@gmail.com>
© 2016 - 2026 Red Hat, Inc.