[PATCH v2 1/2] of: fdt: fix memory leak in fdt_ensure_space
Stefan Kerkmann
s.kerkmann at pengutronix.de
Thu Feb 1 03:28:49 PST 2024
If the reallocation failed the old memory remains allocated and is never
freed, this is fixed by freeing the old memory on error.
Signed-off-by: Stefan Kerkmann <s.kerkmann at pengutronix.de>
Reviewed-by: Ahmad Fatoum <a.fatoum at pengutronix.de>
---
drivers/of/fdt.c | 28 +++++++++++++++++++++-------
1 file changed, 21 insertions(+), 7 deletions(-)
diff --git a/drivers/of/fdt.c b/drivers/of/fdt.c
index 5c21bab5de..544294a9ac 100644
--- a/drivers/of/fdt.c
+++ b/drivers/of/fdt.c
@@ -375,24 +375,38 @@ static void *memalign_realloc(void *orig, size_t oldsize, size_t newsize)
static int fdt_ensure_space(struct fdt *fdt, int dtsize)
{
+ size_t new_size;
+ void *previous;
+
/*
* We assume strings and names have a maximum length of 1024
* whereas properties can be longer. We allocate new memory
* if we have less than 1024 bytes (+ the property size left.
*/
if (fdt->str_size - fdt->str_nextofs < 1024) {
- fdt->strings = realloc(fdt->strings, fdt->str_size * 2);
- if (!fdt->strings)
+ previous = fdt->strings;
+ new_size = fdt->str_size * 2;
+
+ fdt->strings = realloc(previous, new_size);
+ if (!fdt->strings) {
+ free(previous);
return -ENOMEM;
- fdt->str_size *= 2;
+ }
+
+ fdt->str_size = new_size;
}
if (fdt->dt_size - fdt->dt_nextofs < 1024 + dtsize) {
- fdt->dt = memalign_realloc(fdt->dt, fdt->dt_size,
- fdt->dt_size * 2);
- if (!fdt->dt)
+ previous = fdt->dt;
+ new_size = fdt->dt_size * 2;
+
+ fdt->dt = memalign_realloc(previous, fdt->dt_size, new_size);
+ if (!fdt->dt) {
+ free(previous);
return -ENOMEM;
- fdt->dt_size *= 2;
+ }
+
+ fdt->dt_size = new_size;
}
return 0;
--
2.39.2
More information about the barebox
mailing list