A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
memchr scans the first n bytes of a memory block for a specific byte value. It returns a pointer to the first match, or NULL if the byte does not appear. Unlike strchr, it does not stop at a null terminator. It scans exactly n bytes regardless of content. This makes it the right tool for searching binary data, network packets, and any buffer that might contain embedded nulls.
#include <stdio.h>#include <string.h>int main(void) {unsigned char packet[] = {0x48, 0x65, 0x00, 0x6C, 0x6C, 0x6F};size_t len = sizeof(packet);unsigned char *found = memchr(packet, 0x00, len);if (found) {printf("Null byte found at offset %ld\n", found - (unsigned char *)packet);}unsigned char *missing = memchr(packet, 0xFF, len);printf("0xFF search: %s\n", missing ? "found" : "NULL");const char *text = "Hello, World!";char *comma = memchr(text, ',', strlen(text));if (comma) {printf("Comma at index %ld\n", comma - text);}return 0;}
The packet contains an embedded null byte at offset 2. strchr would stop at that null and never see the bytes after it. memchr scans the full 6 bytes and finds it. This is the critical difference: memchr is length-bounded, not terminator-bounded. For binary protocols, this is the only correct search function.
memchr is the binary-safe search. Use it for packets, file headers, serialized data, and any buffer where a null byte is data rather than a terminator. Next: tmpnam, for generating temporary filenames, and why mkstemp is usually a better choice.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.