Jonas Bllessa
Jonas Bllessa

Reputation: 21

memcmp return value, inconsistent comportment

Here is a small C code to highlight an issue on memcmp return value:

    char *str1 = "\200";
    char *str2 = "\0";

    int val1 = memcmp(str1, str2, 2);
    int val2 = memcmp("\200", "\0", 2);

    printf("val 1 : %d \n",val1);
    printf("val 0 : %d \n",val2);

Stdout is:

val 1 : 128
val 2 : -1

Is there an explication for the difference between the 2 functions call? Thanks for your help.

the clang version:

Apple LLVM version 9.0.0 (clang-900.0.39.2) Target: x86_64-apple-darwin16.7.0

Upvotes: 2

Views: 323

Answers (1)

pmg
pmg

Reputation: 108986

According to POSIX documentation, memcmp() internally uses unsigned char.

I suppose your char is signed.

My guess (if I interpret https://godbolt.org/z/iOIbil correctly) is that memcmp() with the literals does not invoke the code in the standard library and the compiler itself replaces the call comparing -1 and 0 ('\200' is 1 + 0b1111111); the memcmp() call with the variables invokes the code in the standard library which converts the originally signed char to unsigned char and compares 128 and 0.

Upvotes: 2

Related Questions