fix return value of wcs{,n}cmp for extreme wchar_t values
authorGabriel Ravier <gabravier@gmail.com>
Wed, 4 Jan 2023 15:07:19 +0000 (16:07 +0100)
committerRich Felker <dalias@aerifal.cx>
Sun, 12 Feb 2023 22:50:59 +0000 (17:50 -0500)
As a result of using simple subtraction to implement the return values
for wcscmp and wcsncmp, integer overflow can occur (producing
undefined behavior, and in practice, a wrong comparison result). This
does not occur for meaningful character values (21-bit range) but the
functions are specified to work on arbitrary wchar_t arrays.

This patch replaces the subtraction with a little bit of code that
orders the characters correctly, returning -1 if the character from
the first string is smaller than the one from the second, 0 if they
are equal and 1 if the character from the first string is larger than
the one from the second.

src/string/wcscmp.c
src/string/wcsncmp.c

index 26eeee7..286ec3e 100644 (file)
@@ -3,5 +3,5 @@
 int wcscmp(const wchar_t *l, const wchar_t *r)
 {
        for (; *l==*r && *l && *r; l++, r++);
-       return *l - *r;
+       return *l < *r ? -1 : *l > *r;
 }
index 4ab32a9..2b3558b 100644 (file)
@@ -3,5 +3,5 @@
 int wcsncmp(const wchar_t *l, const wchar_t *r, size_t n)
 {
        for (; n && *l==*r && *l && *r; n--, l++, r++);
-       return n ? *l - *r : 0;
+       return n ? (*l < *r ? -1 : *l > *r) : 0;
 }