0

I'd like to define a function such that I return a string and a boolean indicating whether the result is valid. Like this:

bool getStringOrTimeout(String *s) {
  ...
  if (timed_out) {
    return false;
  } else {
    *s = String(<some value>);
    return true;
  }
}

Is this going to cause a memory problem because the string is allocated on the stack and deallocated when it leaves scope, or is this okay?

  • You don't need to use the String constructor there. You could just as easily have said: *s = "foo"; – Nick Gammon Mar 13 '16 at 0:36
1

You are better off passing the string by reference, like this:

bool getStringOrTimeout(String & s)
{
  if (timed_out)
    return false;
  s = "foo";
  return true;

}

That means the caller's string will be modified. And you no longer need to pass down a pointer to a string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.