The alloc_anon() function calls malloc() without checking for a NULL
return. If memory allocation fails, a NULL pointer dereference will
occur when accessing the buffer.

Add proper error handling to return -1 when malloc() fails in all
four alloc_anon variants:
- alloc_anon()
- alloc_anon_50M_check()
- alloc_anon_noexit()
- alloc_anon_50M_check_swap()

Signed-off-by: Hongfu Li <[email protected]>
---
 tools/testing/selftests/cgroup/test_memcontrol.c | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/tools/testing/selftests/cgroup/test_memcontrol.c 
b/tools/testing/selftests/cgroup/test_memcontrol.c
index b43da9bc20c4..8ef9c99a82eb 100644
--- a/tools/testing/selftests/cgroup/test_memcontrol.c
+++ b/tools/testing/selftests/cgroup/test_memcontrol.c
@@ -61,6 +61,11 @@ int alloc_anon(const char *cgroup, void *arg)
        char *buf, *ptr;
 
        buf = malloc(size);
+       if (buf == NULL) {
+               fprintf(stderr, "malloc() failed\n");
+               return -1;
+       }
+
        for (ptr = buf; ptr < buf + size; ptr += PAGE_SIZE)
                *ptr = 0;
 
-- 
2.25.1


Reply via email to