Can LOCAL defined Strings cause memory problems?

Hi everybody,

my knowledge about Strings (the one with capital "S" scratches only the surface.

I have read some discussions and some "tutorials" about Strings.
As far as I have understood re-assigning global defined Strings new values again and again can cause memory problems if the initial assigning is not big enough.

local declared Strings get deleted after leaving the function which has the declaration.

example

void myDemoFunction(byte myParameter) {

  if (myParameter == 1) {
    String myLocalString = "I am just local. is this dangerous?";
    Serial.println(myLocalString);
  } 
}

Again: I want to emphasize I have only scratched the surface of how this type of variable work.

Can a variable of type String that is declared inside of an if-condition-block like shown above cause memory-problems?

Is it the same for Strings that are declared inside a "functional block like

  • if-condition?
  • while-loop?
  • for-loop?

best regards Stefan

Hard to answer. Any variable wrong maintained can cause problems. It is important to know well what are you doing. Like in your example, the const string will take place in flash, the also in SRAM as a global variable and then as a copy in the String. Are you aware of it?
Anyway, any local variable's lifetime is within the scope, so as the program jumps out of the function the String variable has gone.
However, one important thing about dynamic variables is that they can fragment a memory and it can be fatal, especially if the memory is small. Nevertheless, I am using it without any problems.

You did not specify the platform, but e.g. in AVR world, debugging in Atmel Studio can help understand these things.

a "one line" String will not be a problem. Not in global scope, nor in local scope.

you should write your example with the concatenation of a string where the compiler has no chance to do some optimization.
Something like

void myDemoFunction(byte myParameter) {

  if (myParameter == 1) {
    String myLocalString;
    myLocalString += "I am just local. is this dangerous? ";
    myLocalString += millis();
    myLocalString += " and more";
    Serial.println(myLocalString);
  } 
}

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.