I have a function which reads in a character, one byte at a time, through the serial port. After these bytes are collected, they are passed to a method to process the bytes and message.
I know how to fix the problem (fix is below), but why do my bytes get truncated when I don’t perform the fix?
unsigned char dpBuf[255];
...
// Pretend dpBuf has values 0x01 0x02 0x03 0x00 0x00 0x00 0x04 0x05
..
ProcessMsg(dpBuf);
..
void ProcessMsg(unsigned char *buff)
{
// buff comes in as 0x01 0x02 0x03 0x00 and rest is truncated
char p[255];
...
for (int i = 0; i < sizeof(buff); i++)
{
sprintf(p, " 0x%X ", (unsigned char)b[i]);
}
..
}
Fix:
ProcessMsg((unsigned char*)&dpBuf, length); // instead of sizeof() in the loop, use length
..
void ProcessMsg (unsigned char *buff, int length)
{
// buff comes in as the original character string and is not truncated
..
// do for loop, print out contents
}
buffis declared asconst char*, sosizeof(buff)returns the size of such a pointer, which seems to be 4 bytes on your machine. Therefore the first four bytes of the buffer are then printed in the loop.It doesn’t matter that
dpBufis declared as an array of larger size because it is passed to the function as a pointer. To circumvent this problem you should add a parameter to the function where the size of the buffer is passed explicitly.