String structure bug
plaurenc opened this issue · comments
Hello Rob,
Thank you for this superb library but I encounter a bug when I try to save a string type structure, I try to save a telephone number in international format for example "+32495030405" the first character is always replaced by a bad one, if i decrease the size like "+324950304" does it work??
Thanks for your help
Pascal
here is the code from an example of the package.
Example 1 return
size: 20
write: 13105
read: 2947
temp: +324950304
hum: 53.10
pres: 1000.90
done...
Example 2 return
size: 20
write: 13105
read: 2947
temp: #32495030405
hum: 53.10
pres: 1000.90
done...
Thanks for the issue, might take a few days before I can investigate.
Had a quick look and the problem is using a String in the struct.
Strings use dynamic memory and can allocate runtime new memory.
Assigning a new value to the String does not expand the struct. See this minimal sketch.
#include "Arduino.h"
struct
{
String temperature;
float humidity;
float pressure;
} measurement;
void setup()
{
Serial.begin(115200);
while (!Serial);
Serial.println(__FILE__);
Serial.println(sizeof(measurement));
measurement.temperature = "123456798123465789123456879X";
Serial.println(sizeof(measurement));
Serial.println(measurement.temperature);
Serial.println(sizeof(measurement.temperature));
}
void loop()
{
}
output
14
14
123456798123465789123456879X
6
Size of the struct does not change after assigning the large String.
The size of 14 = 2x4 for the two floats and 6 bytes for the (reference to the) String.
Solution is to use a char array, something like
struct
{
char temperature[32];
float humidity;
float pressure;
} m2;
this will allocate 32+4+4 = 40 bytes for the struct and should work.
Give it a try
From the String class source code
protected:
char *buffer; // the actual char array
unsigned int capacity; // the array length minus one (for the '\0')
unsigned int len; // the String length (not counting the '\0')
that makes up the 6 bytes allocated for the String.
Use strcpy(measurement.temperature, "12345")
There is also a function String.toCharArray() something like that.
If it works you may close the issue
Ok, otherwise please reopen the issue