[PATCH 1/3] lib: implement strnstr()

Rasmus Villemoes ravi at prevas.dk
Mon Jan 6 11:14:13 CET 2025


On Mon, Jan 06 2025, Jerome Forissier <jerome.forissier at linaro.org> wrote:

>> + *
>> + * Return:	pointer to the first occurrence or NULL
>>   */
>> -char * strstr(const char * s1,const char * s2)
>> +char *strnstr(const char *s1, const char *s2, size_t len)
>>  {
>> -	int l1, l2;
>> +	size_t l1, l2;
>>  
>> +	l1 = strnlen(s1, len);
>>  	l2 = strlen(s2);
>> -	if (!l2)
>> -		return (char *) s1;
>> -	l1 = strlen(s1);
>> -	while (l1 >= l2) {
>> -		l1--;
>> -		if (!memcmp(s1,s2,l2))
>> +
>> +	for (; l1 >= l2; --l1, ++s1) {
>> +		if (!memcmp(s1, s2, l2))
>>  			return (char *) s1;
>> -		s1++;
>>  	}
>> +
>>  	return NULL;
>>  }
>>  #endif
>
> This won't return s1 when s2 == NULL, will it?

Why should it? That's a broken caller. You can't call str* functions
with NULL pointers. It's ok for s2 to point at an empty string, in which
case l2 is 0, so the very first memcmp() is guaranteed to succeed and
yes, this will return s1 in that case.

As passing "" as s2 is likely quite rare, the current short-circuiting
of that case is pointless.

> Why not use a known good implementation such as [1]?
>
> [1] https://github.com/freebsd/freebsd-src/blob/main/lib/libc/string/strnstr.c

Licensing? Also, that's quite unreadable, so please don't.

Rasmus


More information about the U-Boot mailing list