EEprom get function not getting the right amount of bytes?

@sheng, as (I think) @ScruffR pointed out before, you should use strncpy() to protect against index overrun on the char arrays if data is larger than the array has space for. :wink:

1 Like

Exactly, but only for globals.
And with clean stack I meant that there were no previous function calls that placed other values on the stack that would still be there when subsequent function calls reuse the same memory locations. Since the system will always execute pretty much the same functions prior to your own function the "residues" on the stack (where local automatic variables are stored) will mostly be the same. And the String constructor is also a function that will leave some stuff on the stack which can end up in the string as these bytes will be placed back to back with the still present variables of the calling function.
And A only gets its length after all the costruction, heap allocation and string copying has already happened.

For the location of variables I have no good answer, but the optimizer and linker may have a say in that. It may also look different on a completely fresh project with no precompiled modules.

In addition to the sound advice of @peekay123 (which I usually give but seem to have forgotten this time :blush:) when using some strn...() functions you should check how they behave when an operation doesn't fit.
e.g. strncpy() will still leave you with an unterminated string when the buffer is too short.
http://www.cplusplus.com/reference/cstring/strncpy/?kw=strncpy

This is what I meant with this

So the safe use of strncpy() would be

char buf[32];
memset(buf, 0, sizeof(buf));
strncpy(buf, someLongString, sizeof(buf)-1); // keep final zero intact
1 Like

@peekay123, @ScruffR, I definitely learn my lesson on this one. :smile: Thank you all for helping out.

1 Like