Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Detecting errors in String operations #186

Open
BojanJurca opened this issue Mar 16, 2023 · 1 comment
Open

Detecting errors in String operations #186

BojanJurca opened this issue Mar 16, 2023 · 1 comment

Comments

@BojanJurca
Copy link

BojanJurca commented Mar 16, 2023

Hello,

If a String creation fails it is possible to detect this error in the code, like:

String s = "abc";
if (!s) ... // error, out of heap or something ...

However the error detection doesn't work with String expressions:

#define howLarge 5000
String *strArray = new String [howLarge]; 

void wasteAlmostAllMemory () {
  for (int i = 0; i < howLarge; i++) strArray [i] = " wasted memory ";
  while (true)
    for (int i = 0; i < howLarge; i++)
      if (!strArray [i].concat (" more wasted memory "))
        return;
} 

String returnLongString () {
  return "This is a long string, much longer than fits into free memory, although not right now.";
}

void setup () {
    Serial.begin (115200);

    String longString = returnLongString ();

    Serial.printf ("Wasting memory, please wait ... ");
    wasteAlmostAllMemory ();
    Serial.printf ("memory successfuly wasted\n");

    String resultString;

    // 1.
      resultString = longString;
      if (!resultString)
        Serial.printf ("Could not create a long String s.\n"); // error detected successfuly
      else { Serial.print ("'"); Serial.print (resultString); Serial.println ("'"); }

    // 2.
      resultString = "ABC " + longString + " DEF";
      if (!resultString)
        Serial.printf ("Could not calculate a String s.\n"); // error goes by undetected
      else { Serial.print ("'"); Serial.print (resultString); Serial.println ("'"); } // the output is: ' DEF' 

    // 3.
      resultString = returnLongString (); // failure to create the return String crashes the controller
}

void loop () {

}

My proposal is that each string expression that contains string in "error state" result in string also in "error state", so success could be tested only once even after several String operations. Something like this:

    String s = "abc";
    for (int i = 1; i < 1000; i++)
      s += s.substring (1, 1);
    if (!s) ... // error

Thank you.

@BojanJurca

This comment was marked as duplicate.

@arduino arduino locked as too heated and limited conversation to collaborators Oct 7, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant