[ccan] [PATCH 3/3] opt: Don't segfault if a string's default is NULL

Rusty Russell rusty at rustcorp.com.au
Sat Jun 21 17:22:12 EST 2014


Douglas Bagnall <douglas at halo.gen.nz> writes:
> Instead show '(nil)', like other people do. This is distinguishable
> from a similar looking string value, because the latter is shown with
> double quotes while NULL's nil has no quotes.
>
> Signed-off-by: Douglas Bagnall <douglas at halo.gen.nz>

Nice.  This is the kind of thing that only shows up when people start
using a library.

Applied.

Thanks,
Rusty.

> ---
>  ccan/opt/helpers.c | 21 +++++++++++++--------
>  1 file changed, 13 insertions(+), 8 deletions(-)
>
> diff --git a/ccan/opt/helpers.c b/ccan/opt/helpers.c
> index c557f96..43b86d7 100644
> --- a/ccan/opt/helpers.c
> +++ b/ccan/opt/helpers.c
> @@ -202,14 +202,19 @@ void opt_show_invbool(char buf[OPT_SHOW_LEN], const bool *b)
>
>  void opt_show_charp(char buf[OPT_SHOW_LEN], char *const *p)
>  {
> -	size_t len = strlen(*p);
> -	buf[0] = '"';
> -	if (len > OPT_SHOW_LEN - 2)
> -		len = OPT_SHOW_LEN - 2;
> -	strncpy(buf+1, *p, len);
> -	buf[1+len] = '"';
> -	if (len < OPT_SHOW_LEN - 2)
> -		buf[2+len] = '\0';
> +	if (*p){
> +		size_t len = strlen(*p);
> +		buf[0] = '"';
> +		if (len > OPT_SHOW_LEN - 2)
> +			len = OPT_SHOW_LEN - 2;
> +		strncpy(buf+1, *p, len);
> +		buf[1+len] = '"';
> +		if (len < OPT_SHOW_LEN - 2)
> +			buf[2+len] = '\0';
> +	}
> +	else {
> +		strncpy(buf, "(nil)", OPT_SHOW_LEN);
> +	}
>  }
>
>  /* Show an integer value, various forms. */
> --
> 1.8.3.2
> _______________________________________________
> ccan mailing list
> ccan at lists.ozlabs.org
> https://lists.ozlabs.org/listinfo/ccan


More information about the ccan mailing list