Comparing memory blocks with memcmp
What you'll learn: How to determine if two regions of memory contain identical data, regardless of the data type.
The digital magnifying glass
Up to this point, you have likely used strcmp to compare strings or the == operator to compare integers. But what if you need to compare two raw arrays, two structs, or a block of binary data like an image snippet?
This is where memcmp (memory compare) comes in. It treats memory like a long row of bytes. It doesn't care if those bytes represent text, numbers, or pixels; it simply checks if the sequences are identical.
Think of it like two identical-looking suitcases. To be absolutely sure they contain the exact same items in the exact same order, you’d lay them side-by-side and compare them inch-by-inch from bottom to top.
How memcmp works
The function takes three arguments: the two memory addresses to compare and the number of bytes to check.
#include <stdio.h>
#include <string.h>
int main() {
int arr1[] = {10, 20, 30};
int arr2[] = {10, 20, 30};
int arr3[] = {10, 20, 99};
// We compare the size of the entire array
int result = memcmp(arr1, arr2, sizeof(arr1));
if (result == 0) {
printf("arr1 and arr2 are identical.\n");
} else {
printf("arr1 and arr2 are different.\n");
}
return 0;
}
Interpreting the result
Like strcmp, memcmp doesn't return a simple true or false. Instead, it returns an integer:
- 0: The blocks are identical for the specified number of bytes.
- Less than 0: The first differing byte in the first block is smaller than the corresponding byte in the second block.
- Greater than 0: The first differing byte in the first block is larger.
A word of caution
memcmp is incredibly fast because it looks at raw bits. However, it is "blind" to C logic. For example, if you compare two structs, memcmp might claim they are different even if their fields are identical. This happens because structs often contain "padding"—invisible gaps of junk data inserted by the compiler to align memory. Since memcmp checks every single bit, including the junk in the gaps, it may find differences where you didn't expect them.
Key takeaway
Use memcmp to check for equality between two blocks of memory when you know the exact byte count you wish to verify.