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.