This question does not appear to have anything to do with the MCU or the SDK, but as I have no idea anymore what could be going on and I cannot reproduce that issue on any other hardware, at least I would like to share this Voodoo case hoping that someone may have an idea...
I am receiving text messages on a TCP socket using recv. The other side sends one message in one packet but depending on timing, sometimes recv gets more than message at once from the receive buffer. As I need to parse message by message, I am looking for the first newline in the buffer containing the received data "buffer" and then I copy that part to a mailbox structure containing a string element "ac.recv".
"bp = strchr(buffer, 10);" should return a pointer to the first occurrence of character 10 in buffer. For some reason however, I noticed that in some cases it only returns the second occurrence. Here is the code:
n = NDK_recv(s, buffer, sizeof(buffer), 0);
if (n > 1)
{
buffer[n] = 0;
Task_sleep(500);
// look for the stop-character in the buffer
bp = strchr(buffer, 10);
while (bp)
{
i = bp - buffer - 1;
strncpy(ac.recv, buffer, i);
ac.recv[i] = 0;
if (strchr(ac.recv, 10))
{
i++;
}
Mailbox_post(m_sll_in, &ac, BIOS_NO_WAIT);
bp = strchr(bp + 1, 10);
}
}
- Store first match of \n to bp.
- Store the position of bp to i (minus 1 to get rid of \n).
- Copy i characters from buffer to ac.recv.
- Terminate ac.recv at position i.
At this point there is no point at all why ac.recv should recv any \n character and so "strchr(ac.recv, 10)" shall never ever return anything but NULL. But it does!
The debugger stopped at line 214 where you have the i++ statement:
Above you can see value 56 for i and address 0x20014F37 for bp, however buffer has the first "10" at position 28 (0x20014F1A) with 57 (0x20014F37) being the second match out of three.
How can this be? I have done/excluded:
- Replace strchr function by for-loop, same result.
- Add a Task_sleep(500); between recv and strchr just to see if there is "something" going on in the background.
- No other tread is writing into that memory area or executing the same function. All variables are only a function-level.
What I am missing here?!
Thanks to anyone for there comments!
Regards
Peter