E
E
Egor Lepikhin2020-03-06 14:49:36
Arduino
Egor Lepikhin, 2020-03-06 14:49:36

Why does the value of a string in memory change in Arduino?

I have a list of structures which is stored in a class as a pointer to the first element of the list:

Structure
struct SensorValue {
  String name;
  double value;
  bool constantly;
  SensorValue *next;
};

It is written correctly by calling the sendValue method like this:
Entry to the list
void Cloud::sendValue(String name, double value, bool constantly) {
  SensorValue newSensorValue;
  newSensorValue.name = name;
  newSensorValue.value = value;
  newSensorValue.constantly = constantly;
  newSensorValue.next = NULL;

  addSensorValue(&newSensorValue);
}

void Cloud::addSensorValue(SensorValue* value) {
  if (sensorsList == NULL) {
    sensorsList = value;
    return;
  }

  SensorValue* iter = sensorsList;
  while (iter->next != NULL) 
    iter = iter->next;

  (iter->next) = value;
}

But when accessing the first element from another method, the value of the name field is taken as if from thin air:
List access
String requestBody = "{\"login\":\"" + login + "\",";
  requestBody += "\'password\':\"" + password + "\",";
  requestBody += "\"deviceName\":\"" + device + "\",";
  requestBody += "\"deviceType\":\"Arduino\",\"sensorsValue\":{";

 SensorValue* iter = sensorsList;
  Serial.println(sensorsList->name);
  Serial.println(sensorsList->value);
  Serial.println(sensorsList->next == NULL);

In this example, the value sensorsList->name outputs the value "\"deviceName\":\"" + device + "\","; which was concatenated above. And the following 2 values ​​are displayed correctly. It turns out the problem is with the line
Why is this happening and how to fix it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
WinPooh32, 2020-03-06
@LepikhinEgor

SensorValue newSensorValue;
 addSensorValue(&newSensorValue);

Because the address on the structure allocated on a stack undertakes.
You can't do that.
Allocate memory via new or copy.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question