开发者

char buffers comparison

开发者 https://www.devze.com 2023-02-18 01:47 出处:网络
i have two char buffers which i am trying to compare parts of them. i am having a weird problem. i have the following code:

i have two char buffers which i am trying to compare parts of them. i am having a weird problem. i have the following code:

char buffer1[50], buffer2[60]; 
// Get buffer1 and buffer2 from the network by reading sockets
for(int i = 0; i < 20; i++)
{
    if(buffer1[15+i] != buffer2[25开发者_运维百科+i])
    {
        printf("%c", buffer1[15+i]);
        printf("%c", buffer2[25+i]);
        printf("%02x", (unsigned char)buffer1[15+i]);
        printf("%02x", (unsigned char)buffer2[25+i]);
        break;
    }
}

The above code is a simplified version of my actual code which I didnt copy-paste here because its too long. Just in case this might help, I got those two buffer over the network by reading sockets.

The problem is the loop breaks even when both the buffers are the same. To check what is in the buffers, I added the two print statements inside the if statement. And the weird thing is is, the printf statements both print the same value for %c and %02x, but the comparison fails and the loop breaks.


(Disclaimer: I'm not a C/++ expert)

It seems to me like the data is changing while you're looking at it. Two quick questions come to mind:

  1. If you run this in the debugger, and go over the loop step-by-step, does it still happen? If it doesn't, then I strongly suspect my second question will lead you to the answer.
  2. Is the read operation asynchronous? It seems like data is still being read while you're inside the for loop, meaning you didn't wait for the read to finish.


The only thing I see is a timing issue. If they are not the same on the if statement and they are the same on the print statement someone changed them in between.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号