MBED weird memcpy & pointer behaviour for STM32F411

Hi,
I am trying to write some basic application code:
#include <stdio.h>
#include <string.h>

char RxBuf[] = “abc123”;
char TmpBuf[32];
char *p1;
char *p2;

int main()
{
p1 = strstr(RxBuf, “abc”);

memcpy(TmpBuf, p1+strlen("abc"), 3);

printf("String Size: %u\r\n",strlen(TmpBuf));
printf("Actual String: %s",TmpBuf);

return 0;

}

In any other C compiler, the result would be:
String Size: 3
Actual String: 123

but when writing code on a STM32F411RET6, the result is:
String Size: 4
Actual String: 123.

I think this has something to do with pointer alignment, but am not sure what is going on. For larger strings, the behaviour is even more erratic. Why is memcpy copying 4 byes when it should’ve copied only 3 as I specified?

Hello Carel,

My guess is that because the TmpBuf was not initialized with null characters (with zeros) it could happen that there was a random character at TmpBuf[3] which was printed as empty character (space).
Try to initialize the TmpBuf with zeros:

...
char TmpBuf[32] = {};
...

or

...
memset(TmpBuf, 0, 32);
memcpy(TmpBuf, p1+strlen("abc"), 3);
...

Or try to terminate the C-style string with a null character after memcpy:

...
memcpy(TmpBuf, p1+strlen("abc"), 3);
TmpBuf[3] = '\0';
//(or TmpBuf[3] = 0;)
...

Best regards,

Zoltan

Hello Zoltan,
I’ve tried that already - I mean to initialize the whole TmpBuf by writing ‘\0’ to every byte in the array. The result is still the same, which I also don’t understand.

It only happens in Mbed.

Hello Carel,

That’s a very weird behaviour. I tried to reproduce it on my NUCLEO-F446RE but with no success. Have you tried to debug your program with the Mbed Studio IDE to see what is stored in TmpBuf?

BR, Zoltan

Hello Zoltan,
I’m using the online compiler. What is strange to me is since this morning it started working correctly again without me changing any of my code this morning.

What I did notice yesterday is that when I compile code that uses pointers, it behaves strangely and not consistently throughout the day. For some reason, everything is working now so I wonder if it was caused by the online compiler somehow because I was working from work and could not figure out what was wrong, why is the system I’m working on not working. So I worked further from home and the same happened However - since this morning it is working again if I re-compile.

I am pretty sure this was caused by the online compiler - but thanks anyways for your interest in helping me, it is greatly appreciated!

Regards