memcmp(3)

C library function

Compare two regions over n bytes interpreted as unsigned char. Only the sign matters, and both regions must contain the requested bytes.

memcmp(afirst
region
, bsecond
region
, 3count
bytes compared
);

Returns< 0first comes before0equal bytes> 0first comes after

Synopsis
#include <string.h>
int memcmp(const void *s1, const void *s2, size_t n);

Description

memcmp compares the first n bytes of two memory regions in order. Each byte is interpreted as an unsigned char. A null byte doesn't end the comparison: it is part of the binary data. The first difference determines the sign of the result; if all requested bytes match, the result is zero.

Both pointers must designate objects containing at least n readable bytes. The function doesn't receive their capacities and cannot validate them. With a zero count and valid pointers, it returns zero.

Return value

A negative, zero or positive integer according to the order of the regions. Only the sign is portable: test < 0, == 0 or > 0, not a particular magnitude such as == -1.

Pitfalls

Comparing the common prefix of buffers with different lengths doesn't establish complete equality. Check the lengths before comparing the contents.

For null-terminated text, strcmp respects the end of the string; memcmp can compare later bytes. Don't read those bytes without establishing that they belong to the objects and have been initialized.

A structure may contain padding bytes. Equal fields therefore don't imply equal object representations. Compare the fields that define your data contract.

This function doesn't guarantee timing independent of the data. It isn't suitable for a cryptographic comparison that requires this property.

Example

These regions differ only after their null byte. The condition prints 1 because the first buffer comes before the second.

manual.c
#include <stdio.h>#include <string.h>
int main(void){    const unsigned char a[] = {65, 0, 88};    const unsigned char b[] = {65, 0, 89};    printf("%d\n", memcmp(a, b, sizeof a) < 0);    return 0;}
Terminal
$ gcc -std=c17 -Wall -Wextra -Werror manual.c -o manual$ ./manual1
C

memcmp

32-bit

Write gm_memcmp by comparing bytes as unsigned char without stopping at a null byte.

Open the exercise

Now write it yourself.