From 185b1cb1b78d03fccb49f5f58e159450fb3dec39 Mon Sep 17 00:00:00 2001 From: Oki Minabe Date: Sat, 23 Apr 2022 16:23:25 +0900 Subject: [PATCH] libc/string: strcmp/strncmp cast unsigned char Summary: - Cast to unsigned char for strcmp and strncmp - strcmp and strncmp are described following by opengroup.org The sign of a non-zero return value shall be determined by the sign of the difference between the values of the first pair of bytes (both interpreted as type unsigned char) that differ in the strings being compared. https://pubs.opengroup.org/onlinepubs/9699919799/functions/strcmp.html https://pubs.opengroup.org/onlinepubs/9699919799/functions/strncmp.html Impact: - strcmp and strncmp return value Testing: - ostest on sabre-6quad:smp w/ qemu Signed-off-by: Oki Minabe --- libs/libc/string/lib_strcmp.c | 9 ++++++--- libs/libc/string/lib_strncmp.c | 3 ++- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/libs/libc/string/lib_strcmp.c b/libs/libc/string/lib_strcmp.c index 2ac4f62619a..edb6d23c834 100644 --- a/libs/libc/string/lib_strcmp.c +++ b/libs/libc/string/lib_strcmp.c @@ -34,11 +34,14 @@ #undef strcmp /* See mm/README.txt */ int strcmp(FAR const char *cs, FAR const char *ct) { - register signed char result; + register int result; for (; ; ) { - if ((result = *cs - *ct++) != 0 || !*cs++) - break; + if ((result = (unsigned char)*cs - (unsigned char)*ct++) != 0 || + !*cs++) + { + break; + } } return result; diff --git a/libs/libc/string/lib_strncmp.c b/libs/libc/string/lib_strncmp.c index 117f1fddf88..48e2a2486aa 100644 --- a/libs/libc/string/lib_strncmp.c +++ b/libs/libc/string/lib_strncmp.c @@ -37,7 +37,8 @@ int strncmp(const char *cs, const char *ct, size_t nb) int result = 0; for (; nb > 0; nb--) { - if ((result = (int)*cs - (int)*ct++) != 0 || !*cs++) + if ((result = (unsigned char)*cs - (unsigned char)*ct++) != 0 || + !*cs++) { break; }