Subject: Re: [PATCH 2/4] Fix use-after-free warning with GCC at -O3

From: Patrick Steinhardt <[email-masked]>
Date: Wed, 4 Jun 2025 09:36:07 +0200

On Wed, Jun 04, 2025 at 08:06:44AM +0900, Mike Hommey wrote:
> ```
> reftable/basics.c: In function ‘parse_names’:
> reftable/basics.c:233:17: error: pointer ‘names’ may be used after ‘free’ [-Werror=use-after-free]
>   233 |                 reftable_free(names[i]);
>       |                 ^~~~~~~~~~~~~~~~~~~~~~~
> In function ‘reftable_free’,
>     inlined from ‘reftable_realloc’ at reftable/basics.c:30:3,
>     inlined from ‘reftable_realloc’ at reftable/basics.c:27:7,
>     inlined from ‘reftable_alloc_grow’ at reftable/basics.h:228:10,
>     inlined from ‘parse_names’ at reftable/basics.c:214:8:
> reftable/basics.c:44:17: note: call to ‘free’ here
>    44 |                 free(p);
>       |                 ^~~~~~~
> ```

Same here, only posting the warning isn't sufficient to explain what's
going on.

> diff --git a/reftable/basics.c b/reftable/basics.c
> index 9988ebd635..de21fe6ef7 100644
> --- a/reftable/basics.c
> +++ b/reftable/basics.c
> @@ -229,9 +229,11 @@ char **parse_names(char *buf, int size)
>  	return names;
>  
>  err:
> -	for (size_t i = 0; i < names_len; i++)
> -		reftable_free(names[i]);
> -	reftable_free(names);
> +	if (names) {
> +		for (size_t i = 0; i < names_len; i++)
> +			reftable_free(names[i]);
> +		reftable_free(names);
> +	}
>  	return NULL;
>  }

This change shouldn't be needed in theory: `names_len` has a positive
value if and only if `names` is non-NULL. So the warning is a false
positive.

That being said I'm not opposed to squelching this warning. But details
like this should be explained in the commit message.

Patrick