Locate the first occurrence of a byte in a memory block.
The memchr() function scans the first n bytes of the memory area pointed to by ptr for the first occurrence of the byte c (interpreted as an unsigned char). It returns a pointer to the matching byte, or NULL if the byte does not occur in the given block.
The function is declared in <string.h>. Unlike strchr(), which stops at the null terminator, memchr() searches a fixed number of bytes regardless of content, making it suitable for binary data and buffers that may contain embedded nulls.
Common use cases include searching for delimiters in network packets or parsed data, finding line terminators in raw input, and any binary-safe byte search. It is typically implemented in highly optimized assembly using SIMD instructions on modern platforms.
| Name | Description | Optional |
|---|---|---|
ptr |
Pointer to the memory area to scan. | No |
c |
The byte to search for. | No |
n |
Number of bytes to scan. | No |
#include <string.h>
char buf[] = "hello world";
char *p = memchr(buf, 'w', sizeof(buf));
if (p != NULL) {
printf("found at offset %ld\n", p - buf);
}