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?

Nick Gammon
38.9k13 gold badges69 silver badges125 bronze badges
asked Mar 12, 2016 at 21:20
1
  • You don't need to use the String constructor there. You could just as easily have said: *s = "foo"; Commented Mar 13, 2016 at 0:36

1 Answer 1

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.

answered Mar 13, 2016 at 0:34

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.