2

Consider the following piece of code:

void fun (string &str1, string &str2)
{
   const char* cstr;
....
   if(strlen(cstr = (str1+str2).c_str()) < 15)
   {
      // here cstr used
   }
}

The condition itself works fine, but in the if-condition body cstr contains garbage. Why?

1
  • Why are you using strlen when you can use std::string::length? Commented May 7, 2020 at 18:21

2 Answers 2

9

In this expression:

cstr = (str1+str2).c_str()

you are taking a pointer to the temporary string str1 + str2. This temporary dies at the end of the expression, and so you have undefined behaviour when you try to read from cstr inside the if-body.

Sign up to request clarification or add additional context in comments.

Comments

2

I'm assuming the string in your C++ code is std::string.

str1 + str2 produces a temporary std::string object. You invoke the c_str() method on it, and you get a C-style string pointer to the data of this temporary std::string object.

When the temporary std::string goes out of scope and is destroyed, the cstr raw C-style pointer is left dangling, pointing to invalid memory.

If you need to work on the concatenated string str1 + str2, I would suggest you safely store it in a non-temporary std::string object, e.g.:

std::string s = str1 + str2;
// Work with s
if (s.length() < 15) {
    // Use s here
    ...
}

Note also that I invoked the std::string::length() method instead of the C function strlen(). You can use the std::string::size() method, as well.

In general, in C++ code, you should use convenient string classes (like std::string), instead of C-style raw string pointers.

Comments

Your Answer

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.