History

lib/string.c: allow searching for NUL with strnchr

Patch series "lib/string: search for NUL with strchr/strnchr". I noticed an inconsistency where strchr and strnchr do not behave the same with respect to the trailing NUL. strchr is standardised and the kernel function conforms, and the kernel relies on the behavior. So, naturally strchr stays as-is and strnchr is what I change. While writing a few tests to verify that my new strnchr loop was sane, I noticed that the tests for memset16/32/64 had a problem. Since it's all about the lib/string.c file I made a short series of it all... This patch (of 3): strchr considers the terminating NUL to be part of the string, and NUL can thus be searched for with that function. For consistency, do the same with strnchr.

Peter Rosin committed 7 years ago

Commit b0975711 parent 4c6080c1 file · +10 −1Browse files

Showing the changes to lib/string.c (1 of 1 file). Show all

Unified · Split

lib/string.c+10−1
@@ -400,6 +400,9 @@ EXPORT_SYMBOL(strncmp); · 399 unmodified lines
400400 * strchr - Find the first occurrence of a character in a string
401401 * @s: The string to be searched
402402 * @c: The character to search for
403+ *
404+ * Note that the %NUL-terminator is considered part of the string, and can
405+ * be searched for.
403406 */
404407 char *strchr(const char *s, int c)
405408 {
@@ -453,12 +456,18 @@ EXPORT_SYMBOL(strrchr); · 47 unmodified lines
453456 * @s: The string to be searched
454457 * @count: The number of characters to be searched
455458 * @c: The character to search for
459+ *
460+ * Note that the %NUL-terminator is considered part of the string, and can
461+ * be searched for.
456462 */
457463 char *strnchr(const char *s, size_t count, int c)
458464 {
459− for (; count-- && *s != '\0'; ++s)
465+ while (count--) {
460466 if (*s == (char)c)
461467 return (char *)s;
468+ if (*s++ == '\0')
469+ break;
470+ }
462471 return NULL;
463472 }
464473 EXPORT_SYMBOL(strnchr);

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t