I don't understand why when I go to make a comparison between two unint8_t inside a for loop with an if without putting any printf I have that the comparison is not correct.
This code work, I don't have any error:
for (uint16_t i = 0; i < BUFFER_SIZE; i )
{
printf("Position Value: %d -> read %d, expected %d \n", i, RxData[i], TxData[i]);
if (TxData[i] != RxData[i])
{
error ;
}
}
This code doesn't work, I have error:
for (uint16_t i = 0; i < BUFFER_SIZE; i )
{
if (TxData[i] != RxData[i])
{
error ;
}
}
Work -> The two vectors have the same elements, so their comparison does not produce any errors. Doesn't Work -> The two vectors have the same elements but their comparison is not successful and therefore the error variable is increased.
Error is a variable that is incremented if the comparison was not successful.
The behavior of the program changes by putting or not the printf.
Do you know the reason for this? I also tried to put a while loop with a "continue" but I have the same problem.
CodePudding user response:
Judging from the comments on the original question I think what's going on here (without clarification by OP this is conjecture) is something like this:
#define BUFFER_SIZE 256
// returns the actual number of bytes sent, stops and NUL terminator
int send_string(char const *buf, size_t bufsz);
// returns the actual number of bytes received
int receive_some_data(char *buf, size_t bufsz);
int test_interface_loopback()
{
char TxData[BUFFER_SIZE] = "Test Data";
char RxData[BUFFER_SIZE]; // left uninitialized
// return values are ignored -> PROBLEM!
send_some_data(TxData, BUFFER_SIZE);
receive_some_data(RxData, BUFFER_SIZE);
int error = 0;
for( uint16_t i = 0; i < BUFFER_SIZE; i )
{
if( TxData[i] != RxData[i] ){
error ;
}
}
return error;
}
The issue here is, that send_some_data
will for some reason not transmit the whole 256 bytes, but perform only a short write. This might be for example, because it's assuming a C nul terminated string; but it could be also for other reasons like system buffer limitations, or maybe the bytes haves just been queued for sending, but weren't flushed out of the interface.
Either way, receive_some_data
does not actually read 256 bytes, but less. And as such the remainder of RxData
is left uninitialized and thus the comparison invokes undefined behavior.
The proper solution lies in taking into account the actual amount of data being valid in the two buffers.