4 ms·
the code is not exactly memcmp, because the sign of the result doesn't match the sign of memcmp. I verified this with my favorite open source C program prover,
by jepler 10y ago
the code is not exactly memcmp, because the sign of the result doesn't match the sign of memcmp. I verified this with my favorite open source C program prover, CBMC http://www.cprover.org/cbmc/ http://www.cprover.org/cbmc/
You can see that CBMC proves that (1) a zero result from mycmp guarantees a zero result from memcmp, and (2) a nonzero result from mycmp guarantees a nonzero result fro mycmp. But (3) a negative result from mycmp doesn't guarantee a negative result from memcmp and (4) a positive result doesn't guarantee a positive result.
So, modulo problems with "strict aliasing" in modern C standards, you can use this code to compare blocks of memory for equality, but you cannot use it to order blocks according to a less-than or greater-than predicate.
https://gist.github.com/jepler/760cfcd4b326d6d11241256a6a4c7a48 https://gist.github.com/jepler/760cfcd4b326d6d11241256a6a4c7...
- feelix 10y agoYes, that's true, because memcmp returns the sign based on the first byte, and this compares four bytes, on little endian architectures it may return the sign differently from the built-in memcmp(). That should be mentioned along with the caveats, that it's not a suitable drop-in replacement when people are not simply testing that the result is 0 (which I imagine to be the majority of cases).