sprintf() causes Arduino to reset

Hi everybody,

I'm having problems getting sprintf() to work on a Mega 2560. The code I use always works when it is put directly into the loop, but when I put it into a function, it causes the Arduino to (seemingly) reset once the function returns.

For example

    char remainingBuf[5];
    sprintf(remainingBuf, "%2i/10", numRemaining);
    tft.print(remainingBuf);

I've already checked and I have over 3Kb of memory left when this function is being ran.

I have very little background in C so I'm sure there's something I'm missing. Any ideas?

sprintf(remainingBuf, "%2i/10", numRemaining);

This does NOT divide numRemaining by 10 and then write the result as an int with at least two places. It writes the int with a minimum pf two places (could be more) then the string "/10" and a NULL. That's 6 or more elements that you are trying to fit in a 5 element array.

Sorry I didn't make that clear, I want the function to print the number remaining "out of ten," so that format string does what I want it to do...

I changed the buffer to 6 to accommodate the NULL and now it works. I didn't realize that sprintf terminated with a NULL. Thanks.

Just to clarify, why would this have worked in the loop?

Just to clarify, why would this have worked in the loop?

You are writing off the end of the array. That never works, for my definition of work. What is possibly did in your case was step on some memory that you didn't notice got stepped on. When you put the code in a function, what is likely stepped on is the return address. THAT you do notice getting stepped on.

It likely means that it found a null somewhere nearby in memory your string didn't own, but that was good enough that you saw no ill effects.

For future reference, all strings should have a null termination at the end - that is the only thing that makes a string distinguishable from an array.

gwsmyda:
I didn't realize that sprintf terminated with a NULL.

While sprintf() does add a NULL to the end, this isn't a sprintf() thing.
All strings in C are terminated with a NULL, that is how the end of the string is marked.
So "hello" takes up 6 bytes
and "%2i/10" takes up 7 bytes.

--- bill

This sort of problem is avoided if you use snprintf() instead of sprintf().

PeterH:
This sort of problem is avoided if you use snprintf() instead of sprintf().

But only if you specify the correct size for the array, and only if you understand that snprintf() will NOT generate the output you expect if the array is too small.

Better to make the array large enough in the first place. IMHO.