Searching memory bytes with memchr
What you'll learn: How to scan a block of memory for the first occurrence of a specific byte value.
In previous lessons, you learned how to copy or set memory blocks using memcpy or memset. However, there are times when you don't want to change memory, but rather find something specific inside it. This is where memchr (Memory Character) comes in.
Scanning the haystacks
Think of memchr like a high-speed metal detector. You give it a starting point, the specific "metal" (byte) you are looking for, and a distance to scan. It doesn't care if the memory contains a string, an array of integers, or raw pixel data; it treats everything as a sequence of individual bytes.
The function signature looks like this:
void *memchr(const void *ptr, int value, size_t num);
- ptr: The starting address of the memory block.
- value: The byte you are looking for (passed as an
int, but converted to anunsigned char). - num: The maximum number of bytes to search.
If the function finds the byte, it returns a pointer to that specific location. If it reaches the limit (num) without finding it, it returns NULL.
Example: Finding a marker
Imagine you have a data buffer and you need to find where a specific "header" byte (like 0xFF) starts so you can process the data following it.
#include <stdio.h>
#include <string.h>
int main() {
unsigned char data[] = { 0x10, 0x20, 0x30, 0xFF, 0x50, 0x60 };
size_t size = sizeof(data);
// Search for the byte 0xFF within the 'data' array
unsigned char *result = memchr(data, 0xFF, size);
if (result != NULL) {
// We found it! We can calculate the index by subtracting pointers
printf("Found 0xFF at index: %ld\n", result - data);
} else {
printf("Byte not found.\n");
}
return 0;
}
Why not just use strchr?
You might remember strchr for searching strings. The critical difference is that strchr stops as soon as it hits a null terminator (\0). memchr does not. Because memchr requires you to provide a specific size, it is safe to use on binary data where a zero byte might just be part of the data rather than the end of the "sentence." It is a robust tool for navigating raw buffers and binary files.
Key takeaway
memchr locates the first occurrence of a byte in a memory block of a specific size, returning a pointer to the match or NULL if not found.