Consider:
constexpr char s1[] = "a";
constexpr char s2[] = "abc";
std::memcmp(s1, s2, 3);
If memcmp
stops at the first difference it sees, it will not read past the second byte of s1 (the nul terminator), however I don't see anything in the C standard to confirm this behavior, and I don't know of anything in C++ which extends it.
n1570 7.24.4.1 PDF link
int memcmp(const void *s1, const void *s2, size_t n);
The
memcmp
function compares the firstn
characters of the object pointed to bys1
to the first n characters of the object pointed to bys2
Is my understanding correct that the standard describes the behavior as reading all n
bytes of both arguments, but libraries can short circuit as-if they did?
s1
in this example. – Cumshawstrncmp
instead ofmemcmp
. – Fezzanstrcmp()
. There is nothing in the specification ofmemcmp()
which requires the bytes to be compared sequentially, or that specifies circumstances in which any bytes in either sequence not be accessed. Sincesizeof(s1) < 3
, yourmemcpy()
call has undefined behaviour. – Rollmop