Question

I just happened to debug an incredibly nasty error: On my own PC (Windows 7 x64, MinGw) my C program would successfully sort an array using the memcmp when comparing array members.

My function used bubble sort algorithm and it's skeleton would look like this:

void array_sort(ArrayMap *array, char direction) {
    make sure direction is +1 or -1 only
    define some variables
    for(...) {
         for(...) {
             cmpres = memcmp(elm1, elm2, sizeOfElement);
             if (cmpres!=0&&cmpres!=direction)
             {
                 SWAP here
             }
         }
}

Now while on my PC, the memcmp has returned -1, 0 and 1 on another it returned -5, 0 and 5. By comparing this with direction I caused the sorting to go totally wrong.

But I wonder, what does the absolute value (that is, the size) of the return value of memcmp actually mean?

From the www.cplusplus.com:

Returns an integral value indicating the relationship between the content of the memory blocks: A zero value indicates that the contents of both memory blocks are equal. A value greater than zero indicates that the first byte that does not match in both memory blocks has a greater value in ptr1 than in ptr2 as if evaluated as unsigned char values; And a value less than zero indicates the opposite.

No mention of the size, they just make sure not to be wrong about +-1 by saying greater than zero.

Was it helpful?

Solution 2

The result magnitude implementation-specific, so it has no portable meaning and you should not rely on it. The memcmp() function is only guaranteed to return a positive, negative, or zero value.

The reason why it is allowed to have any value is so memcmp() can be defined like this:

// Types changed to "char" to simplify code.
int memcmp(const unsigned char *x, const unsigned char *y, size_t n)
{
    for (size_t i = 0; i < n; i++) {
        int diff = x[i] - y[i];
        if (diff)
            return diff;
}

But it can also be implemented by using, e.g., SSE, and the return value will be different.

OTHER TIPS

The documentation says:

The memcmp() function shall return an integer greater than, equal to, or less than 0, if the object pointed to by s1 is greater than, equal to, or less than the object pointed to by s2, respectively.

It doesn't say it will return -1 or 1. What it exactly returns is implementation dependent.

Update:

When implementing a comparison function, you often write:

return a[i] - b[i];

Instead of:

if (a[i] > b[i])
    return 1;
else
    return -1;

That's one possible implementation that explains the numbers that are returned.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top