[PATCH 2/2] lib: Fix sbi_strchr to correctly handle null terminator search
cp0613 at linux.alibaba.com
cp0613 at linux.alibaba.com
Fri Mar 6 01:44:25 PST 2026
From: Chen Pei <cp0613 at linux.alibaba.com>
The original sbi_strchr implementation did not conform to the C standard
behavior. According to the C standard and POSIX specification, strchr(s, 0)
should return a pointer to the null terminator at the end of string s.
The previous implementation used a while loop that would terminate when
either reaching the end of string or finding the character, but it would
return NULL when searching for the null terminator instead of returning
a pointer to the null terminator itself.
The fixed implementation uses a do-while loop that ensures even when
searching for the null terminator, the function correctly returns a
pointer to the null terminator position rather than NULL.
This fix ensures sbi_strchr behavior aligns with standard library
function semantics, making it more predictable and safe for users
expecting standard C library behavior.
Signed-off-by: Chen Pei <cp0613 at linux.alibaba.com>
---
lib/sbi/sbi_string.c | 11 +++++------
1 file changed, 5 insertions(+), 6 deletions(-)
diff --git a/lib/sbi/sbi_string.c b/lib/sbi/sbi_string.c
index f4f13942..3a10c254 100644
--- a/lib/sbi/sbi_string.c
+++ b/lib/sbi/sbi_string.c
@@ -88,13 +88,12 @@ char *sbi_strncpy(char *dest, const char *src, size_t count)
char *sbi_strchr(const char *s, int c)
{
- while (*s != '\0' && *s != (char)c)
- s++;
+ do {
+ if (*s == (char)c)
+ return (char *)s;
+ } while (*s++ != '\0');
- if (*s == '\0')
- return NULL;
- else
- return (char *)s;
+ return NULL;
}
char *sbi_strrchr(const char *s, int c)
--
2.50.1
More information about the opensbi
mailing list