Skip to content

Commit 9be0623

Browse files
jimmodpgeorge
authored andcommitted
shared/libc/string0: Don't deref args for n==0 case.
C99 says that strncmp has UB for either string being NULL, so the current behavior is technically correct, but it's an easy fix to handle this case correctly. 7.1.4: "unless explicitly stated otherwise in the detailed description... if an argument to a function has ...null pointer.. the behavior is undefined". 7.21.1: "Unless explicitly stated otherwise in the description of a particular function in this subclause, pointer arguments on such a call shall still have valid values, as described in 7.1.4". Also make the same change for the minimal version in bare-arm/lib.c. This work was funded through GitHub Sponsors. Signed-off-by: Jim Mussared <[email protected]>
1 parent bea6ff8 commit 9be0623

2 files changed

Lines changed: 3 additions & 2 deletions

File tree

ports/bare-arm/lib.c

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,8 +110,9 @@ char *strchr(const char *s, int c) {
110110
}
111111

112112
int strncmp(const char *s1, const char *s2, size_t n) {
113-
while (*s1 && *s2 && n-- > 0) {
113+
while (n > 0 && *s1 && *s2) {
114114
int c = *s1++ - *s2++;
115+
--n;
115116
if (c) {
116117
return c;
117118
}

shared/libc/string0.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ int strcmp(const char *s1, const char *s2) {
154154
}
155155

156156
int strncmp(const char *s1, const char *s2, size_t n) {
157-
while (*s1 && *s2 && n > 0) {
157+
while (n > 0 && *s1 && *s2) {
158158
char c1 = *s1++; // XXX UTF8 get char, next char
159159
char c2 = *s2++; // XXX UTF8 get char, next char
160160
n--;

0 commit comments

Comments
 (0)