Is there a way to dispose an Arduino String() to free memory?

3.3k views Asked by At

Is there a way to dispose an Arduino String-Object, so the memory it uses gets freed up, when the String is not needed anymore?

I didn't find a function in the reference for this, and when I call free(&str), an Exception is thrown.

Thanks in advance for your help. Simon

Edit: I code with the Arduino-IDE, like this

void setup() {
  // a few setup things
}

void loop() {
  String str1 = "some json String";
  String str2 = str1.substring(10);
  String str3 = jsonRemoveWhiteSpace(str2);
  // so at this point I'd like to dispose of str1 and str2 to free up the memory, 
  // because the strings are also quite long json strings.
}
1

There are 1 answers

3
JohnFilleau On BEST ANSWER

You can use curly braces to make explicit scopes. The C++ standard requires that objects declared in a scope are destroyed when they go out of scope. For objects that manage dynamic memory (such as String) that means the dynamic memory will be released to the system.

void loop() {
  String str3;
  {
    // explicit scope begins here...

    String str1 = "some json String";
    String str2 = str1.substring(10);

    str3 = jsonRemoveWhiteSpace(str2);

    // ...and ends here
  }
  // at this point str1 and str2 go out of scope, and are destroyed
  // str3 was declared outside of the scope, so is fine
}

If it doesn't affect the variable naming too much, you can consider assigning the result of substring and jsonRemoveWhiteSpace to the String you're operating on. The assignment operator for String is well behaved and releases memory as expected.

String str = "some json String";
str = str.substring(10);
str = jsonRemoveWhiteSpace(str);

or

String str = "some json String";
str = jsonRemoveWhiteSpace(str.substring(10));