From fbe86ce8a65007ecdcb76e7f47dc6585f35f788b Mon Sep 17 00:00:00 2001 From: Tobias Stoeckmann Date: Wed, 21 Aug 2024 22:06:58 +0200 Subject: [PATCH] libkmod: Fix memory leak on error path If realloc fails, do not override the still valid pointer with NULL. Otherwise freeing the iterator won't free the previously allocated buffer. Signed-off-by: Tobias Stoeckmann Reviewed-by: Emil Velikov Link: https://github.com/kmod-project/kmod/pull/82 Signed-off-by: Lucas De Marchi --- libkmod/libkmod-builtin.c | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/libkmod/libkmod-builtin.c b/libkmod/libkmod-builtin.c index 40a7d614..825e3a72 100644 --- a/libkmod/libkmod-builtin.c +++ b/libkmod/libkmod-builtin.c @@ -127,13 +127,18 @@ static off_t get_string(struct kmod_builtin_iter *iter, off_t offset, offset += (off_t) partsz; if (iter->bufsz < linesz + partsz) { - iter->bufsz = linesz + partsz; - iter->buf = realloc(iter->buf, iter->bufsz); + void *tmp; + size_t s; - if (!iter->buf) { + s = linesz + partsz; + tmp = realloc(iter->buf, s); + + if (!tmp) { sv_errno = errno; goto fail; } + iter->bufsz = s; + iter->buf = tmp; } strncpy(iter->buf + linesz, buf, partsz);