Skip to content

Commit

Permalink
fix str[n]len implementations
Browse files Browse the repository at this point in the history
The current implementations do not count the length of empty strings
correctly.
The following buffer content "\0foo\0" is considered a string with
length 4, because the iteration pointer is incremented before
it is dereferenced to check for a null char.

Replace the broken strlen functions with the implementation of musl libc.
  • Loading branch information
fischerling committed Mar 1, 2024
1 parent 082ea79 commit c8db92b
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 10 deletions.
9 changes: 4 additions & 5 deletions libc/src/string.c
Original file line number Diff line number Diff line change
Expand Up @@ -489,15 +489,14 @@ char *strcpy(char *dst, const char *src)
size_t strlen(const char *s)
{
const char *it = s;
while (*(++it) != 0) {}
return ((it - s) < 0) ? 0 : (size_t)(it - s);
for (; *it; it++);
return (size_t)(it - s);
}

size_t strnlen(const char *s, size_t count)
{
const char *it = s;
while ((*(++it) != 0) && --count) {}
return ((it - s) < 0) ? 0 : (size_t)(it - s);
const char *p = memchr(s, 0, count);
return p ? (size_t)(p-s) : count;
}

int strcmp(const char *s1, const char *s2)
Expand Down
9 changes: 4 additions & 5 deletions mentos/src/klib/string.c
Original file line number Diff line number Diff line change
Expand Up @@ -488,15 +488,14 @@ char *strcpy(char *dst, const char *src)
size_t strlen(const char *s)
{
const char *it = s;
while (*(++it) != 0) {}
return ((it - s) < 0) ? 0 : (size_t)(it - s);
for(; *it; it++);
return (size_t)(it - s);
}

size_t strnlen(const char *s, size_t count)
{
const char *it = s;
while ((*(++it) != 0) && --count) {}
return ((it - s) < 0) ? 0 : (size_t)(it - s);
const char *p = memchr(s, 0, count);
return p ? (size_t)(p-s) : count;
}

int strcmp(const char *s1, const char *s2)
Expand Down

0 comments on commit c8db92b

Please sign in to comment.