[PATCH] pinctrl: berlin: fix memory leak in berlin_pinctrl_build_state()

Yuan Chen posted 1 patch 3 months, 3 weeks ago
drivers/pinctrl/berlin/berlin.c | 8 ++++++--
1 file changed, 6 insertions(+), 2 deletions(-)
[PATCH] pinctrl: berlin: fix memory leak in berlin_pinctrl_build_state()
Posted by Yuan Chen 3 months, 3 weeks ago
From: Yuan Chen <chenyuan@kylinos.cn>

In the original implementation, krealloc() failure handling incorrectly
assigned the original memory pointer to NULL after kfree(), causing a
memory leak when reallocation failed.

Fixes: de845036f997 ("pinctrl: berlin: fix error return code of berlin_pinctrl_build_state()")
Signed-off-by: Yuan Chen <chenyuan@kylinos.cn>
---
 drivers/pinctrl/berlin/berlin.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)

diff --git a/drivers/pinctrl/berlin/berlin.c b/drivers/pinctrl/berlin/berlin.c
index c372a2a24be4..9dc2da8056b7 100644
--- a/drivers/pinctrl/berlin/berlin.c
+++ b/drivers/pinctrl/berlin/berlin.c
@@ -204,6 +204,7 @@ static int berlin_pinctrl_build_state(struct platform_device *pdev)
 	const struct berlin_desc_group *desc_group;
 	const struct berlin_desc_function *desc_function;
 	int i, max_functions = 0;
+	struct pinfunction *new_functions;
 
 	pctrl->nfunctions = 0;
 
@@ -229,12 +230,15 @@ static int berlin_pinctrl_build_state(struct platform_device *pdev)
 		}
 	}
 
-	pctrl->functions = krealloc(pctrl->functions,
+	new_functions = krealloc(pctrl->functions,
 				    pctrl->nfunctions * sizeof(*pctrl->functions),
 				    GFP_KERNEL);
-	if (!pctrl->functions)
+	if (!new_functions) {
+		kfree(pctrl->functions);
 		return -ENOMEM;
+	}
 
+	pctrl->functions = new_functions;
 	/* map functions to theirs groups */
 	for (i = 0; i < pctrl->desc->ngroups; i++) {
 		desc_group = pctrl->desc->groups + i;
-- 
2.25.1
Re: [PATCH] pinctrl: berlin: fix memory leak in berlin_pinctrl_build_state()
Posted by Linus Walleij 3 months, 2 weeks ago
On Fri, Jun 20, 2025 at 3:53 AM Yuan Chen <chenyuan_fl@163.com> wrote:

> From: Yuan Chen <chenyuan@kylinos.cn>
>
> In the original implementation, krealloc() failure handling incorrectly
> assigned the original memory pointer to NULL after kfree(), causing a
> memory leak when reallocation failed.
>
> Fixes: de845036f997 ("pinctrl: berlin: fix error return code of berlin_pinctrl_build_state()")
> Signed-off-by: Yuan Chen <chenyuan@kylinos.cn>

Patch applied!

Yours,
Linus Walleij