]> git.armaanb.net Git - sic.git/commitdiff
util: trim() fix for UB on pointer arithmetic
authorHiltjo Posthuma <hiltjo@codemadness.org>
Thu, 6 May 2021 10:18:21 +0000 (12:18 +0200)
committerHiltjo Posthuma <hiltjo@codemadness.org>
Thu, 6 May 2021 10:20:30 +0000 (12:20 +0200)
Follow-up fix on commit df4c0611366bf361fa263fbc57009cbe68456855

"
While it is true reversing the condition solves a single-byte read at
one before s, there is a second instance of UB.

Having a pointer to one before an object is in of itself UB in C, it's
on the side of language lawyering, but it's UB.
I add here a quote from a C standard draft:
> When an expression that has integer type is added to or subtracted
> from a pointer, the result has the type of the pointer operand.
> If both the pointer operand and the result point to elements of the
> same array object, or one past the last element of the array object,
> the evaluation shall not produce an overflow; otherwise, the
> behavior is undefined.
Taken from: http://www.iso-9899.info/n1570.html#6.5.6p8
"

Thanks Guilherme Janczak <guilherme.janczak@yandex.com>

util.c

diff --git a/util.c b/util.c
index cb966d43c89ae24bae1afcdf32e7136f8ef68367..8cea8836cf6dc14dbadb5394201b45cda9dc0d34 100644 (file)
--- a/util.c
+++ b/util.c
@@ -60,8 +60,7 @@ static void
 trim(char *s) {
        char *e;
 
-       e = s + strlen(s) - 1;
-       while(e > s && isspace((unsigned char)*e))
-               e--;
-       *(e + 1) = '\0';
+       for (e = s + strlen(s); e > s && isspace((unsigned char)*(e - 1)); e--)
+               ;
+       *e = '\0';
 }