summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authordzwdz2022-12-27 22:31:48 +0100
committerdzwdz2022-12-27 22:31:48 +0100
commita54c80d07bbaa8cb34dd5924d0926ac47e7deded (patch)
treec8f6c842bfc36e69d220af4768a9edd61af457c8
parent9ab2c4468e0352da0fa13de355124f25b6af5ad3 (diff)
libc: fix strncmp
-rw-r--r--src/user/app/tests/libc/string.c3
-rw-r--r--src/user/lib/string/string.c9
2 files changed, 7 insertions, 5 deletions
diff --git a/src/user/app/tests/libc/string.c b/src/user/app/tests/libc/string.c
index 2e00049..6afe350 100644
--- a/src/user/app/tests/libc/string.c
+++ b/src/user/app/tests/libc/string.c
@@ -55,6 +55,9 @@ static void test_strcmp(void) {
test(0 < strcmp("string", "str"));
test(0 != strcmp("stress", "string"));
+
+ test(0 != strncmp("abc", "ab", 3));
+ test(0 == strncmp("abc", "ab", 2));
}
static void test_strtol(void) {
diff --git a/src/user/lib/string/string.c b/src/user/lib/string/string.c
index f141a3d..126d175 100644
--- a/src/user/lib/string/string.c
+++ b/src/user/lib/string/string.c
@@ -109,12 +109,11 @@ char *strtok_r(char *restrict s, const char *restrict sep, char **restrict state
}
int strncmp(const char *s1, const char *s2, size_t n) {
- while (n-- & *s1 && *s1 == *s2) {
- s1++; s2++;
+ for (size_t i = 0; i < n; i++) {
+ if (s1[i] < s2[i]) return -1;
+ if (s1[i] > s2[i]) return 1;
}
- if (*s1 == *s2) return 0;
- if (*s1 < *s2) return -1;
- else return 1;
+ return 0;
}
int strcoll(const char *s1, const char *s2) {