Skip to content
Tutorials Center
My learning

Topics

C Reference ยท string.h

C memcmp() function

Reference for C memcmp(): compare two blocks of bytes, understand the sign of the result, and avoid its traps with structs, floats and endianness.

memcmp() compares the first n bytes of two memory blocks. It treats the bytes as unsigned char values and returns zero if all are equal, otherwise a negative or positive number according to the first pair that differs. Unlike strcmp, it does not stop at a null byte, so it works on binary data.

It is a good fit for comparing byte arrays such as hashes, UUIDs and fixed-size records. It is a poor fit for comparing structs and numbers, for reasons covered below.

C
#include <string.h>

int memcmp(const void *s1, const void *s2, size_t n);

Try it

C Comparing byte arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C Where memcmp gives surprising answers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Syntax

C
int memcmp(const void *s1, const void *s2, size_t n);
Name Description
s1, s2 The blocks to compare.
n The number of bytes to compare.

Returns: zero if the blocks are equal, a negative value if the first differing byte is smaller in s1, and a positive value if it is larger.

Errors / undefined behavior: both blocks must be readable for n bytes. NULL is undefined, even for n == 0.

Usage notes

  • Only the sign is meaningful, not the magnitude. Test with == 0, < 0 or > 0.
  • Byte order. On little-endian machines memcmp on integers does not follow numeric order, as the example shows. Compare numbers with < and ==. Big-endian encodings (network order, many hash outputs) do compare correctly byte-wise.
  • Struct comparison is unreliable. Padding bytes between members have indeterminate values unless you zeroed the whole object first, and members such as pointers or float may compare unequal despite meaning the same. Compare field by field.
  • Floating point. 0.0 and -0.0 differ in bytes, NaN payloads vary. Use == on the values.
  • Strings: memcmp needs an explicit length and ignores terminators; for ordinary strings, strcmp is the correct tool. To compare exactly the text of two strings of known length, memcmp is fine.
  • Secrets. memcmp may return at the first difference, which leaks timing information. For MACs and passwords, use a constant-time comparison from a cryptography library.
  • Ordering with qsort: memcmp is a convenient comparator for fixed-size byte keys.
  • Zero length: memcmp(a, b, 0) returns 0 for valid pointers.