简体   繁体   中英

Memcmp seems to be giving me an incorrect return value

I have two unsigned char arrays of the same size and an if statement that checks to see if they're equal:

    #define BUFFER_SIZE 10000

    unsigned char origChar[BUFFER_SIZE];
    unsigned char otherChar[BUFFER_SIZE];

    //Yes, I know this is unnecessary

    memset(origChar,'\0',BUFFER_SIZE);
    memset(otherChar,'\0',BUFFER_SIZE);

    . . .
    if(memcmp(origChar,otherChar,offset))
    {
        . . .
    }

When I examine the two arrays in gdb, I get the following:

(gdb) p origChar
$1 = '\000' <repeats 9999 times>
(gdb) p otherChar
$2 = '\000' <repeats 9999 times>...
(gdb) p memcmp(otherChar,origChar,offset)
$3 = 1

However, if I decrement offset by 1, I get the following:

(gdb) p memcmp(otherChar,origChar,offset-1)
$4 = 0
(gdb) p offset
$5 = 10000

It doesn't really make any sense to me. GDB basically says they're completely equal, so why would decrementing offset by one change things?

Well... Reading your dump, I can tell you that origChar and otherChar are both '\\0'*9999 ; while you're trying to compare the first 10000 bytes when using offset. So there is probably a difference in the 10000'th byte.

Using offset-1 , you're comparing the first 9999 bytes, hence the equality.

The "bug" thus comes from something you do in your first " . . . " that modifies the 10000'th value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM