Hi All,

While running a piece of code on Linux and HP i found the differenc in the result.
Can Anyone Explain Why it is giving different results?

#include <stdio.h>

int main()
    int a = 0;
    int b = 30030;
    int c = 34094;
    int d = 0 ;
    d = memcmp(&b,&c,sizeof(int));
    printf ("Comparison between b and c : %d",d);
    return 0;

On HP : This returns : “Comparison between b and c : -16”
On Linux This returns : “Comparison between b and c : 1”

4 Years
Discussion Span
Last Post by Learningvinit

The more common convention would be 1, 0, or -1. The standard may allow any value > 0 < 0 or 0 (as is seen with strcmp(), a very similar function).

The negative value in one, and the positive value in the other, is a problem however. Could it be that the sizeof(int) is different on these systems, when you print it out?

Edited by Adak


Could you be more specific about the OSes in question? I suspect that it's an endianness issue. I'm not aware of HP-UX support on little endian architectures, but Linux supports both big and little endian depending on the hardware. If you're running Linux on something like an x86 then I'm not surprised you're getting reversed results from the two platforms.


I imagine this is an endian issue. When storing an integer in memory little endian processors store least significant byte first, big endian processors store most significant byte first.

So the numbers are stored in memory as follows

little endian machine: 4E 75 00 00
big endian machine:    00 00 75 4E

little endian machine: 2E 85 00 00
big endian machine:    00 00 85 2E

Taking -16 to mean second one bigger and 1 to mean first one bigger and remembering that memcmp compares a byte at a time then.

On a little endian, Linux, it compares
1st Byte: 4E with 2E; they are different, 4E is bigger so the first parameter is bigger so it returns 1 and stops.

On big endian, HP, it compares:
1st Byte: 00 with 00, the same continue to 2nd byte
2nd Byte: 00 with 00, the same continue to 3rd byte
3rd Byte: 75 with 85; they are different, 75 is smaller so return negative. It is doing the comparison by subtraction and returning the result if it is not 0, 0x75 - 0x85 = -16

That is how you get different results on different machines with them both being correct.

Edited by Banfa

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.