diff mbox series

[ethtool,v2,11/13] ethtool: fix missing free of memory after failure

Message ID 20221208011122.2343363-12-jesse.brandeburg@intel.com (mailing list archive)
State Changes Requested
Delegated to: Michal Kubecek
Headers show
Series ethtool: clean up and fix | expand

Checks

Context Check Description
netdev/tree_selection success Not a local patch

Commit Message

Jesse Brandeburg Dec. 8, 2022, 1:11 a.m. UTC
cppcheck warns:
test-common.c:106:2: error: Common realloc mistake: 'block' nulled but not freed upon failure [memleakOnRealloc]
 block = realloc(block, sizeof(*block) + size);
 ^

Fix the issue by storing a local copy of the old pointer and using that
to free the original if the realloc fails, as the manual for realloc()
suggests.

Signed-off-by: Jesse Brandeburg <jesse.brandeburg@intel.com>
---
 test-common.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)

Comments

Michal Kubecek Dec. 8, 2022, 10:52 a.m. UTC | #1
On Wed, Dec 07, 2022 at 05:11:20PM -0800, Jesse Brandeburg wrote:
> cppcheck warns:
> test-common.c:106:2: error: Common realloc mistake: 'block' nulled but not freed upon failure [memleakOnRealloc]
>  block = realloc(block, sizeof(*block) + size);
>  ^
> 
> Fix the issue by storing a local copy of the old pointer and using that
> to free the original if the realloc fails, as the manual for realloc()
> suggests.
> 
> Signed-off-by: Jesse Brandeburg <jesse.brandeburg@intel.com>

Acked-by: Michal Kubecek <mkubecek@suse.cz>

> ---
>  test-common.c | 9 ++++++---
>  1 file changed, 6 insertions(+), 3 deletions(-)
> 
> diff --git a/test-common.c b/test-common.c
> index e4dac3298577..b472027140f6 100644
> --- a/test-common.c
> +++ b/test-common.c
> @@ -97,15 +97,18 @@ void test_free(void *ptr)
>  
>  void *test_realloc(void *ptr, size_t size)
>  {
> -	struct list_head *block = NULL;
> +	struct list_head *block = NULL, *oldblock;
>  
>  	if (ptr) {
>  		block = (struct list_head *)ptr - 1;
>  		list_del(block);
>  	}
> -	block = realloc(block, sizeof(*block) + size);
> -	if (!block)
> +	oldblock = block;
> +	block = realloc(oldblock, sizeof(*oldblock) + size);
> +	if (!block) {
> +		free(oldblock);
>  		return NULL;
> +	}
>  	list_add(block, &malloc_list);
>  	return block + 1;
>  }
> -- 
> 2.31.1
>
diff mbox series

Patch

diff --git a/test-common.c b/test-common.c
index e4dac3298577..b472027140f6 100644
--- a/test-common.c
+++ b/test-common.c
@@ -97,15 +97,18 @@  void test_free(void *ptr)
 
 void *test_realloc(void *ptr, size_t size)
 {
-	struct list_head *block = NULL;
+	struct list_head *block = NULL, *oldblock;
 
 	if (ptr) {
 		block = (struct list_head *)ptr - 1;
 		list_del(block);
 	}
-	block = realloc(block, sizeof(*block) + size);
-	if (!block)
+	oldblock = block;
+	block = realloc(oldblock, sizeof(*oldblock) + size);
+	if (!block) {
+		free(oldblock);
 		return NULL;
+	}
 	list_add(block, &malloc_list);
 	return block + 1;
 }