简体   繁体   English

Memcmp似乎给我不正确的返回值

[英]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: 我有两个大小相同的无符号字符数组,以及一个if语句,检查它们是否相等:

    #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中的两个数组时,得到以下信息:

(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: 但是,如果我将offset量减1,则会得到以下结果:

(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? GDB基本上说它们是完全相等的,那么为什么递减offset会改变事情呢?

Well... Reading your dump, I can tell you that origChar and otherChar are both '\\0'*9999 ; 好吧...阅读您的转储,我可以告诉您origCharotherChar都是'\\0'*9999 ; while you're trying to compare the first 10000 bytes when using offset. 当您尝试使用偏移量比较前10000个字节时。 So there is probably a difference in the 10000'th byte. 因此,第10000个字节中可能存在差异。

Using offset-1 , you're comparing the first 9999 bytes, hence the equality. 使用offset-1 ,您正在比较前9999个字节,因此相等。

The "bug" thus comes from something you do in your first " . . . " that modifies the 10000'th value. “虫”,因而来自于你在第一次做什么“ ”可修改10000'th值。 . . .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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