Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

char buffers comparison

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.

like image 788
Romonov Avatar asked May 08 '26 22:05

Romonov


1 Answers

(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.
like image 77
configurator Avatar answered May 10 '26 12:05

configurator



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!