libs/libc/string: fix memmem() boundary case when needle is at end of haystack

This fixes calls like memmem("hello", 5, "lo", 2);

Also zero-length needle is deemed to exist at beginning of haystack.
This behavior matches memmem() on Linux, FreeBSD, NetBSD and OpenBSD.

Signed-off-by: Juha Niskanen <juha.niskanen@haltian.com>
This commit is contained in:
Juha Niskanen
2024-03-11 12:40:43 +02:00
committed by Xiang Xiao
parent 68c21df444
commit 47026978bf
+6 -1
View File
@@ -51,12 +51,17 @@ FAR void *memmem(FAR const void *haystack, size_t haystacklen,
size_t i; size_t i;
size_t y; size_t y;
if (needlelen == 0)
{
return (void *)haystack;
}
if (needlelen > haystacklen) if (needlelen > haystacklen)
{ {
return NULL; return NULL;
} }
for (i = 0; i < haystacklen - needlelen; i++) for (i = 0; i <= haystacklen - needlelen; i++)
{ {
y = 0; y = 0;
while (h[i + y] == n[y]) while (h[i + y] == n[y])