In C, memchr() searches a block of memory for the first byte that matches a value. It looks at exactly n bytes. It does not stop early at a '\0'.
You pass the memory, the byte to find, and how many bytes to scan. All three are required. The result is a pointer to the match, or NULL when it is missing. Include <string.h>.
Syntax
Pass the block, the byte, and the count. Start with this call.
C
memchr(buf, 'A', 5);
Call
What it does
memchr(buf, 'A', 5)
Looks at the first 5 bytes of buf for the byte 'A'.
Include <string.h>. Check the result for NULL before you use the pointer.
Library declarations
C
void *memchr(const void *s, int c, size_t n);
Parameters
Parameter
Description
s
Required. The memory to search.
c
Required. The byte to find, often written as a character in single quotes.
n
Required. How many bytes to scan.
Return Value
Return Value
Description
Pointer
Points to the first matching byte inside the same block.
NULL
Returned when that byte is not found in the first n bytes.
C Examples
Example 1 — Find a Character and Its Index
Search for 'C' in "Hello, C!" and print the zero-based index.
C
#include <stdio.h>
#include <string.h>
int main(void) {
const char *str = "Hello, C!";
char needle = 'C';
void *p = memchr(str, needle, strlen(str));
if (p != NULL) {
size_t index = (const char *)p - str;
printf("'%c' found at index %zu\n", needle, index);
} else {
printf("'%c' not found\n", needle);
}
return 0;
}
Output
'C' found at index 7
How It Works
Measure the string.strlen(str) is 9, so memchr scans only the visible characters.
Search for the byte. Each byte is compared to 'C' until index 7 matches.
Check for NULL. A non-null result means a match exists inside the block.
Get the index. Subtract the base pointer: (const char *)p - str → 7.
Example 2 — Search Only the First n Bytes
A smaller n can miss a byte that appears later in the buffer.
C
#include <stdio.h>
#include <string.h>
int main(void) {
const char *text = "ABC-DEF";
void *dash;
dash = memchr(text, '-', 3); /* only "ABC" */
if (dash == NULL) {
printf("No dash in first 3 bytes\n");
}
dash = memchr(text, '-', 4); /* "ABC-" */
if (dash != NULL) {
printf("Dash at index %td\n", (const char *)dash - text);
}
return 0;
}
Output
No dash in first 3 bytes
Dash at index 3
How It Works
First call uses n = 3. Only "ABC" is scanned; '-' is at index 3, so the result is NULL.
Second call uses n = 4. The range includes the dash at index 3.
n is the boundary.memchr never stops at '\0'—only n limits the scan.
Use this for prefixes. Handy when a buffer has a header length you must not read past.
Example 3 — Search a Binary Buffer
memchr() works when there is no null terminator—ideal for packets and raw bytes.