What does size of the memcmp return value mean?

六眼飞鱼酱① 提交于 2019-12-04 05:11:30

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/23618328/what-does-size-of-the-memcmp-return-value-mean

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!