diff options
| author | Jim Mussared <jim.mussared@gmail.com> | 2023-11-06 15:06:28 +1100 |
|---|---|---|
| committer | Damien George <damien@micropython.org> | 2023-11-07 16:01:50 +1100 |
| commit | 9be0623d4ce518eead8ea477a4615cb8c3e357d8 (patch) | |
| tree | bce6af7160ad9a59532f03a3c6b7506685385093 | |
| parent | bea6ff82fadf37555a3a282105f861a914475bb6 (diff) | |
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 undeļ¬ned".
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 <jim.mussared@gmail.com>
| -rw-r--r-- | ports/bare-arm/lib.c | 3 | ||||
| -rw-r--r-- | shared/libc/string0.c | 2 |
2 files changed, 3 insertions, 2 deletions
diff --git a/ports/bare-arm/lib.c b/ports/bare-arm/lib.c index 61d3be64e..1574d5c90 100644 --- a/ports/bare-arm/lib.c +++ b/ports/bare-arm/lib.c @@ -110,8 +110,9 @@ char *strchr(const char *s, int c) { } int strncmp(const char *s1, const char *s2, size_t n) { - while (*s1 && *s2 && n-- > 0) { + while (n > 0 && *s1 && *s2) { int c = *s1++ - *s2++; + --n; if (c) { return c; } diff --git a/shared/libc/string0.c b/shared/libc/string0.c index a3b268e44..3909f70ed 100644 --- a/shared/libc/string0.c +++ b/shared/libc/string0.c @@ -154,7 +154,7 @@ int strcmp(const char *s1, const char *s2) { } int strncmp(const char *s1, const char *s2, size_t n) { - while (*s1 && *s2 && n > 0) { + while (n > 0 && *s1 && *s2) { char c1 = *s1++; // XXX UTF8 get char, next char char c2 = *s2++; // XXX UTF8 get char, next char n--; |
