Re: [hackers] [st][PATCH] fix pointer to one before object UB

From: Hiltjo Posthuma <hiltjo_AT_codemadness.org>
Date: Thu, 6 May 2021 01:50:48 +0200

On Wed, May 05, 2021 at 09:34:15PM +0000, Guilherme Janczak wrote:
> The expression "s + strlen(s) - 1" can create a pointer to one before
> *s if strlen(s) is 0.
>
> ---
> util.c | 14 +++++++++-----
> 1 file changed, 9 insertions(+), 5 deletions(-)
>
> diff --git a/util.c b/util.c
> index bdba718..c97f491 100644
> --- a/util.c
> +++ b/util.c
> _AT_@ -59,9 +59,13 @@ skip(char *s, char c) {
> static void
> trim(char *s) {
> char *e;
> -
> - e = s + strlen(s) - 1;
> - while(isspace(*e) && e > s)

Hi,

Thanks for the patch. It seems indeed to read out-of-bounds 1 byte before the
buffer if the input is empty.

I think if the condition is reversed then it is fine:

> - while(isspace(*e) && e > s)

to:

> - while(e > s && isspace(*e))

I'll apply this and a few small changes tomorrow.

> - e--;
> - *(e + 1) = '\0';
> +
> + e = s + strlen(s);
> + while (e > s) {
> + if (!isspace(*--e)) {
> + e++;
> + *e = '\0';
> + break;
> + }
> + }
> }
> --
> 2.31.1
>
>

-- 
Kind regards,
Hiltjo
Received on Thu May 06 2021 - 01:50:48 CEST

This archive was generated by hypermail 2.3.0 : Thu May 06 2021 - 02:00:37 CEST