[klibc] [klibc:master] strstr, memmem: Handle zero-length needle correctly

klibc-bot for Ben Hutchings ben at decadent.org.uk
Fri Dec 30 14:03:13 PST 2022


Commit-ID:  bf50476c204f7eab1fba5370a49fb03fcfaf92d1
Gitweb:     http://git.kernel.org/?p=libs/klibc/klibc.git;a=commit;h=bf50476c204f7eab1fba5370a49fb03fcfaf92d1
Author:     Ben Hutchings <ben at decadent.org.uk>
AuthorDate: Fri, 30 Dec 2022 22:48:59 +0100
Committer:  Ben Hutchings <ben at decadent.org.uk>
CommitDate: Fri, 30 Dec 2022 23:01:22 +0100

[klibc] strstr, memmem: Handle zero-length needle correctly

strstr(haystack, "") and memmem(haystack, n, needle, 0) should
return haystack, not NULL.

- Handle the !m and (m > n || !n) cases separately at the top.
- Delete the !n condition.  After handling !m we know m > 0,
  so checking for !n is redundant with m > n.

Signed-off-by: Ben Hutchings <ben at decadent.org.uk>

---
 usr/klibc/memmem.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)

diff --git a/usr/klibc/memmem.c b/usr/klibc/memmem.c
index 8b5faa00..72422aa4 100644
--- a/usr/klibc/memmem.c
+++ b/usr/klibc/memmem.c
@@ -18,7 +18,10 @@ void *memmem(const void *haystack, size_t n, const void *needle, size_t m)
 
 	size_t j, k, l;
 
-	if (m > n || !m || !n)
+	if (!m)
+		return (void *)haystack;
+
+	if (m > n)
 		return NULL;
 
 	if (1 != m) {


More information about the klibc mailing list