[PATCH v2] recordmcount: Fix memory leaks in the uwrite function

Hao Zeng posted 1 patch 2 years, 7 months ago
There is a newer version of this series
scripts/recordmcount.c | 9 ++++++++-
1 file changed, 8 insertions(+), 1 deletion(-)
[PATCH v2] recordmcount: Fix memory leaks in the uwrite function
Posted by Hao Zeng 2 years, 7 months ago
Common realloc mistake: 'file_append' nulled but not freed upon failure

Signed-off-by: Hao Zeng <zenghao@kylinos.cn>
Suggested-by: Steven Rostedt <rostedt@goodmis.org>
---
 scripts/recordmcount.c | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)

diff --git a/scripts/recordmcount.c b/scripts/recordmcount.c
index e30216525325..efeec898f632 100644
--- a/scripts/recordmcount.c
+++ b/scripts/recordmcount.c
@@ -110,6 +110,7 @@ static ssize_t uwrite(void const *const buf, size_t const count)
 {
 	size_t cnt = count;
 	off_t idx = 0;
+	void *p = NULL;
 
 	file_updated = 1;
 
@@ -117,7 +118,13 @@ static ssize_t uwrite(void const *const buf, size_t const count)
 		off_t aoffset = (file_ptr + count) - file_end;
 
 		if (aoffset > file_append_size) {
-			file_append = realloc(file_append, aoffset);
+			p = realloc(file_append, aoffset);
+			if (!p) {
+				free(file_append);
+				file_append = NULL;
+			} else {
+				file_append = p;
+			}
 			file_append_size = aoffset;
 		}
 		if (!file_append) {
-- 
2.37.2
Re: [PATCH v2] recordmcount: Fix memory leaks in the uwrite function
Posted by Steven Rostedt 2 years, 7 months ago
On Tue, 25 Apr 2023 10:46:03 +0800
Hao Zeng <zenghao@kylinos.cn> wrote:

> @@ -117,7 +118,13 @@ static ssize_t uwrite(void const *const buf, size_t const count)
>  		off_t aoffset = (file_ptr + count) - file_end;
>  
>  		if (aoffset > file_append_size) {
> -			file_append = realloc(file_append, aoffset);
> +			p = realloc(file_append, aoffset);
> +			if (!p) {
> +				free(file_append);
> +				file_append = NULL;
> +			} else {
> +				file_append = p;
> +			}

You can simplify the above with:

			if (!p)
				free(file_append);

			file_append = p;

-- Steve

>  			file_append_size = aoffset;
>  		}
>  		if (!file_append) {