[PATCH] kunit: fix resource leak when init fails

From: Jiangshan Yi

Date: Wed Nov 18 2026 - 04:39:15 EST


If the init function passed to kunit_alloc_resource() or
kunit_alloc_and_get_resource() fails, __kunit_add_resource() returns
before the resource is added to the test's resource list, so the
allocated resource is never freed. Call kfree() on the error path.

The free function is not called on this path: init() is responsible for
cleaning up after a failure, and free() expects an initialized resource.

Fixes: 0a756853586c ("kunit: test: add test resource management API")
Cc: stable@xxxxxxxxxxxxxxx
Signed-off-by: Jiangshan Yi <yijiangshan@xxxxxxxxxx>
---
include/kunit/resource.h | 3 +++
1 file changed, 3 insertions(+)

diff --git a/include/kunit/resource.h b/include/kunit/resource.h
index c330ed3e751c..5c12b3cc2947 100644
--- a/include/kunit/resource.h
+++ b/include/kunit/resource.h
@@ -258,6 +258,8 @@ kunit_alloc_and_get_resource(struct kunit *test,
kunit_get_resource(res);
return res;
}
+
+ kfree(res);
return NULL;
}

@@ -293,6 +295,7 @@ static inline void *kunit_alloc_resource(struct kunit *test,
if (!__kunit_add_resource(test, init, free, res, context))
return res->data;

+ kfree(res);
return NULL;
}

--
2.25.1