The memcmp() function from <string.h> compares the first n bytes of two memory blocks. It returns zero when they match, or a negative or positive value when the first differing byte is smaller or larger—using unsigned char comparison rules.
01
Compare n Bytes
Two memory blocks.
02
Returns int
0, <0, or >0.
03
Unsigned Bytes
0–255 range.
04
Any Memory
Not just strings.
05
Prefix Match
Compare first n only.
06
vs strcmp()
Null-terminated.
Fundamentals
Definition and Usage
In C, memcmp() is declared in <string.h>. It walks through two memory regions in parallel, comparing bytes until either a difference is found or n bytes have been examined. The comparison treats each byte as unsigned char, so values 128–255 sort after 0–127.
Unlike strcmp(), memcmp() does not stop at a null terminator. You control exactly how many bytes are compared—making it suitable for strings, struct padding, network buffers, and any raw memory.
💡
Beginner Tip
Test equality with memcmp(a, b, n) == 0. For sorting, use the sign: negative means a is “less than” b over the first n bytes. The exact numeric return value is implementation-defined—only zero vs non-zero (and sign for ordering) is portable.
Foundation
📝 Syntax
The standard library declaration:
C
int memcmp(const void *s1, const void *s2, size_t n);
Parameters
s1 — pointer to the first memory block.
s2 — pointer to the second memory block.
n — number of bytes to compare.
Return Value
0 — all n bytes are equal.
< 0 — first differing byte in s1 is less than in s2 (as unsigned char).
> 0 — first differing byte in s1 is greater than in s2.
Header
#include <string.h>
Cheat Sheet
⚡ Quick Reference
Block 1
Block 2
Call
Result
"Hello, C!"
"Hello, D!"
memcmp(s1, s2, 7)
0 (prefix match)
"Hello, C!"
"Hello, D!"
memcmp(s1, s2, 9)
< 0 ('C' < 'D')
"abc"
"abc"
memcmp(s1, s2, 3)
0
"beta"
"alpha"
memcmp(s1, s2, 4)
> 0 ('b' > 'a')
equality test
any blocks
memcmp(a, b, n) == 0
true if equal
Equal?
memcmp(a, b, n) == 0
n-byte equality
Prefix
memcmp(s1, s2, 7)
First 7 bytes only
Strings
memcmp(a, b, strlen(a))
When lengths match
Alternative
strcmp(a, b)
Null-terminated C-strings
Hands-On
Examples Gallery
Compile with gcc memcmp.c -std=c11 -o memcmp. Each example interprets the return value and shows when prefix comparison differs from full comparison.
📚 Getting Started
Compare a fixed number of bytes and read the result.
Example 1 — Equal Prefix (First 7 Bytes)
Compare the first 7 characters of "Hello, C!" and "Hello, D!"—both share "Hello, ".
C
#include <stdio.h>
#include <string.h>
int main(void) {
char str1[] = "Hello, C!";
char str2[] = "Hello, D!";
int result = memcmp(str1, str2, 7);
if (result == 0) {
printf("The first 7 bytes are equal.\n");
} else if (result < 0) {
printf("First differing byte in str1 is less than str2.\n");
} else {
printf("First differing byte in str1 is greater than str2.\n");
}
return 0;
}
📤 Output:
The first 7 bytes are equal.
How It Works
Indices 0–6 are identical in both strings ("Hello, "). The differing characters 'C' and 'D' appear at index 7, which is outside the 7-byte comparison range.
Example 2 — Detect the First Difference
Compare 9 bytes to include the character that differs.
C
#include <stdio.h>
#include <string.h>
int main(void) {
char str1[] = "Hello, C!";
char str2[] = "Hello, D!";
int result = memcmp(str1, str2, 9);
if (result == 0) {
printf("Equal for 9 bytes.\n");
} else if (result < 0) {
printf("str1 is less (e.g. 'C' < 'D' at index 7).\n");
} else {
printf("str1 is greater.\n");
}
return 0;
}
📤 Output:
str1 is less (e.g. 'C' < 'D' at index 7).
How It Works
At index 7, 'C' (67) is less than 'D' (68), so memcmp returns a negative value. Increasing n beyond the first difference does not change the sign of the result.
📈 Practical Patterns
Full equality, binary data, and comparison with strcmp().
Example 3 — Compare Entire C-Strings by Length
When both strings have the same length, compare that many bytes for full equality.
memcmp(a, b, strlen(a)) compares visible characters only when lengths match. If lengths differ, use strcmp or compare lengths first before calling memcmp.
Example 4 — Compare Binary Buffers
memcmp() works on any bytes—not only printable text.
C
#include <stdio.h>
#include <string.h>
int main(void) {
unsigned char buf1[] = { 0x01, 0x02, 0x03, 0x04 };
unsigned char buf2[] = { 0x01, 0x02, 0xFF, 0x04 };
int r = memcmp(buf1, buf2, sizeof buf1);
if (r == 0) {
printf("Buffers are identical.\n");
} else if (r < 0) {
printf("buf1 is less at first mismatch (0x03 vs 0xFF).\n");
} else {
printf("buf1 is greater.\n");
}
return 0;
}
📤 Output:
buf1 is less at first mismatch (0x03 vs 0xFF).
How It Works
At index 2, 0x03 (3) is less than 0xFF (255) when treated as unsigned char. strcmp() cannot compare such buffers reliably because they may contain embedded null bytes.
Example 5 — memcmp() vs strcmp()
See how null termination affects strcmp() but not bounded memcmp().
strcmp stops when s1 hits '\0' while s2 still has characters, so it reports inequality. memcmp(s1, s2, 4) compares only "test" and returns 0. Comparing 7 bytes includes extra characters in s2, so the result is negative.
Applications
🚀 Common Use Cases
Fixed-length records — verify two struct or packet headers match for n bytes.
Prefix checks — test whether a buffer starts with a magic number or protocol tag.
Sorting keys — compare fixed-size keys in custom sort routines (sign of return value).
The function receives the start addresses of both blocks and how many bytes to compare.
Input
2
Compare byte by byte
Each pair of bytes is compared as unsigned char until a mismatch or n bytes are done.
Scan
3
Return relationship
Return 0 if all bytes match; otherwise return <0 or >0 based on the first difference.
Result
=
⚖️
int result
Use == 0 for equality, or the sign for lexicographic ordering over fixed-length data.
Important
📝 Notes
Bytes are compared as unsigned char—signed char on the platform does not change the comparison rules inside memcmp.
Ensure n does not read past the end of either valid buffer—that is undefined behavior.
If n is 0, no bytes are compared and the function returns 0.
The magnitude of a non-zero return is not standardized—only the sign is reliably portable for ordering.
For null-terminated C-strings of unknown equal length, strcmp() is usually simpler than choosing n manually.
Performance
⚡ Optimization
Standard library implementations of memcmp() are heavily optimized—often using word-sized reads on aligned data. For typical buffer sizes, calling memcmp directly is faster and clearer than hand-written byte loops. Avoid comparing more bytes than necessary; pick the smallest correct n.
Wrap Up
Conclusion
memcmp() is the standard tool for comparing two memory regions byte by byte. Remember the three outcomes—zero, negative, positive—pick n carefully, and use unsigned-char semantics when reasoning about binary data.
Practice the examples, then continue to memcpy() for copying memory between buffers.
Interpret non-zero results by sign, not exact value
Match string lengths before comparing full C-strings with memcmp
❌ Don’t
Assume return value is always -1 or +1
Pass n larger than allocated memory
Use memcmp on unequal-length strings without checking length
Confuse byte search (memchr) with comparison (memcmp)
Rely on memcmp alone for secret equality in security-critical code
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about memcmp()
Use these points whenever you compare raw memory in C.
5
Core concepts
⚖️01
Compare n Bytes
Two memory blocks.
Basics
📝02
0 / <0 / >0
Three outcomes.
Return
🔢03
Unsigned char
Byte comparison.
Rule
📈04
Prefix OK
Compare first n only.
Pattern
💬05
vs strcmp()
Null-terminated.
Compare
❓ Frequently Asked Questions
memcmp() compares the first n bytes of two memory blocks byte by byte. It returns 0 if all n bytes match, a negative value if the first differing byte in the first block is less, or a positive value if it is greater (using unsigned char comparison).
int memcmp(const void* s1, const void* s2, size_t n); Include <string.h>. Parameters s1 and s2 point to the blocks to compare; n is how many bytes to examine.
0 when the n bytes are identical. A value less than 0 when the first mismatch in s1 is smaller than in s2. A value greater than 0 when the first mismatch in s1 is larger. Only the sign matters for ordering—not the exact number.
memcmp() compares exactly n bytes and works on any memory—including binary data without null terminators. strcmp() compares null-terminated C-strings until '\0'. Use memcmp when you know the length; use strcmp for plain text C-strings.
No. It always compares exactly n bytes. If a null byte appears within those n bytes, it is compared like any other byte. This differs from strcmp(), which stops at the first '\0'.
Yes—compare strlen(s1) bytes only if both strings are the same length, or compare a fixed prefix with memcmp(s1, s2, n). For full C-string equality, strcmp(s1, s2) == 0 is simpler when both are null-terminated.
Did you know?
The mem* functions treat memory as bytes, not characters or Unicode code points. Comparing UTF-8 text with memcmp is a byte-wise lexicographic order—which may differ from locale-aware alphabetical sorting used in user interfaces.