Memcmp implementation

The following is the implementation of memcmp in Microsoft CRT:

int memcmp(const void* buf1,
           const void* buf2,
           size_t count)
{
    if(!count)
        return(0);

    while(--count && *(char*)buf1 == *(char*)buf2 ) {
        buf1 = (char*)buf1 + 1;
        buf2 = (char*)buf2 + 1;
    }

    return(*((unsigned char*)buf1) - *((unsigned char*)buf2));
}

It basically does a comparison of bytes by bytes.

My question has two parts:

  • Is there any reason not to change this for int by comparing int to count < sizeof(int)and then compare bytes by bytes for what remains?
  • If I did 1, are there any potential / obvious issues?

Notes: I do not use CRT at all, so I have to implement this function anyway. I'm just looking for advice on how to implement it correctly.

+5
source share
8 answers

You can do this as an int-by-int comparison or an even wider data type if you want.

, ( ), - , , .

, , ( ).

, , , char int, int , char , , , , , .

, , , , . , , .

+6

, , . , , - , , ; x86 .

, , .

+5

, , char , (memcmp() , unsigned char).

+1

int, , sizeof (int) ( char).

0

? , , -:

  • .
  • return? unsigned char - unsigned char= int?

int , , , - , , 1 , char int-at-time, -, , , , .

memcmp (.. ), ( ), .

, , , , , .

0

. , , , .

0

- . , . , . , .

Psuedo:

while bytes remaining > (cache size) / 2 do // Half the cache for source, other for dest.
  fetch source bytes
  fetch destination bytes
  perform comparison using fetched bytes
end-while
perform byte by byte comparison for remainder.

"Data Driven Design" "Data- ".

, ARM, ( 32-, ) . , , . . , .

. .
. .

, , .

0

, , memcmp, , .

, , ( ) , . , , (buf1 == buf2). .

, , , - , , :

  • ?
  • , ?
  • ?
  • Can the buffer size be 0?
  • You only need to compare the contents of the buffer for equality? Or do you also need to know which one is larger (return value <0 or> 0)?
  • ...

If performace is a concern, I suggest writing a comparison procedure in the assembly. Most compilers give you the opportunity to see the assembly assembly that they generate for the source. You can take this code and adapt it to your needs.

0
source

All Articles