Why does memcmp return a negative value when there is a positive difference?

1k Views Asked by At
#include <stdio.h>
#include <string.h>

int main()
{
    int test1 = 8410092;    // 0x8053EC
    int test2 = 8404974;    // 0x803FEE
    char *t1 = ( char*) &test1;
    char *t2 = (char*) &test2;
    int ret2 = memcmp(t1,t2,4);

    printf("%d",ret2);

}

Here's a very basic function that when run prints -2. Maybe I am totally misunderstanding memcmp, but I thought if it returns the difference between the first different bytes. Since test1 is a larger num than test2, shouldn't the printed value be positive?

I am using the standard gcc.7 compiler for ubuntu.

2

There are 2 best solutions below

0
On BEST ANSWER

As pointed out in the comments, memcmp() runs byte comparison. Here is a man quote

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

RETURN VALUE: The memcmp() function returns an integer less than, equal to, or greater than zero if the first n bytes of s1 is found, respectively, to be less than, to match, or be greater than the first n bytes of s2 For a nonzero return value, the sign is determined by the sign of the difference between the first pair of bytes (interpreted as unsigned char) that differ in s1 and s2. If n is zero, the return value is zero. http://man7.org/linux/man-pages/man3/memcmp.3.html

If the bytes are not the same, the sign of the difference depends on the target endianness.

One application of memcmp() is testing if two large arrays are the same, which could be faster than writing a loop that runs element by element comparison. Refer to this stack questions for more details. Why is memcmp so much faster than a for loop check?

0
On

memcmp compares memory. That is, it compares the bytes used to represent objects. The bytes used to represent objects may vary from one C implementation to another. Per C 2018 6.2.6 2:

Except for bit-fields, objects are composed of contiguous sequences of one or more bytes, the number, order, and encoding of which are either explicitly specified or implementation-defined.

To compare the values represented by objects, use the ordinary operators <, <=, >, >=, ==, and !=. Comparing the memory of objects with memcmp should be used for limited purposes, such as inserting objects into a tree that only needs to be able to store and retrieve items without caring about what their values mean.