Hi
I have been using in dtosrtf() in a relatively big project and some usual stuff was happening. Long story short, I took "The caller is responsible for providing sufficient storage in s" not as serious as I should. I thought if I do not provide enough width it automatically understand not to write in the rest of the memory.
This is very surprising for me and for those who may have a hard time believing it, I have written a little code here.
volatile float numberInput = -3, zero = 0;
char buf[50];
void setup()
{
Serial.begin(115200);
Serial.println("begin");
numberInput = 99999999999999999999999999999999999.0;
dtostrf(numberInput, 5, 1, buf);
// expectation: it will not go beyond 5 character in the buffer
// reality: it goes and screw all the data in the memmory
// question: how do we do this safely?
Serial.write(buf, 50);
Serial.println();
}
And the result in serial port was shocking
100000000000000000000000000000000000.0..............
The . represent 0x00. (checked with non Arduino serial monitor). No surprise there.
And just to show how dangerous it can get, the following code it keeps printing "begi" in serial port. (it continuously start from the start of the program) (I just changed buffer size to 5 instead of 50)
volatile float numberInput = -3, zero = 0;
char buf[5];
void setup()
{
Serial.begin(115200);
Serial.println("begin");
numberInput = 99999999999999999999999999999999999.0;
dtostrf(numberInput, 5, 1, buf);
// expectation: it will not go beyond 5 character in the buffer
// reality: it goes and screw all the data in the memmory
// question: how do we do this safely?
Serial.write(buf, 50);
Serial.println();
}
When I was suspicious of dtostrf(), I taught looking at the implementation would help (I asked in forum). However, I was very wrong but in case that helps you to come up with a solution, you can check the implementation here:
By safe and reasonable, I am looking for a solution where I do not have to worry if I do not provide enough space. I prefer to get acknowledged that the operation was not successful rather than the whole memory being screwed. BTW I am not asking for a magical solution, so I let the function know how much space it has in the buffer, so that it does not go all over the place.
Regarding dtosrtf: I initially taught the width is in charge of telling the limits and right now I do not even know what the width does.
Someone in another forum suggested using 100 byte array to be safe, but I think this is not a reasonable solution on a AVR/Arduino with limited memory.