-2

Consider the MWE below,

std::string return_string() 
{
    return "this is a string"
}
int main()
{
    const char *y = return_string().c_str();
    std::string str = return_string();
    const char *x = str.c_str();

    std::cout << return_string() << std::endl; //Prints "this is a string"
    std::cout << y << std::endl;  // Prints Weird characters
    std::cout << x << std::endl;  //Prints "this is a string"

    std::cin.ignore();
    return 0;
}

I have a function which returns a string and I need to convert it to a c-style string. Doing return_string().c_str() gives me weird output like ▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌p. But if I store the output of a function in a string first and then convert that string to a c-style string it works. What is wrong with the first way?

7
  • The string returned in return_string is a temporary. A pointer (like char*) will not preserve the lifetime of that temporary. Commented May 18, 2017 at 19:07
  • 3
    As an aside, it appears today is a slow day. Everyone is racing to write their own answer to a question that has been asked a dozen times. Commented May 18, 2017 at 19:11
  • 2
    @voidlife: No worries on your part. The answerers know better. Duplicates: 1 2 3 4 5 6 7 8 9 10 11 12 There's more, too Commented May 18, 2017 at 19:26
  • 2
    Duplicates round two: 13 14 15 16 17 18 19 20 21 22 23 24 Commented May 18, 2017 at 19:34
  • 2
    Duplicates round three 25 26 27 28 29 30 31 32 33 34 35 36 37 Commented May 18, 2017 at 19:43

3 Answers 3

4

When you do return_string().c_str() you get the pointer to a temporary object that will go out of scope once the expression is finished. If you save the pointer and use it later you will have undefined behavior.

With

std::string str = return_string();

you copy the returned temporary object. Getting a pointer to the copy will work since it still exists in the program at the point when you use the pointer.

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

Comments

1
const char *y = return_string().c_str();

is a problem if you wish to use y later to access the contents. In that line, the return value of return_string() is a temporary that gets destroyed after that line is executed. Hence, y is dangling pointer.

Accessing the contents of a dangling pointer causes undefined behavior.

When you use

std::string str = return_string();
const char *x = str.c_str();

x is not a dangling pointer as long as str is in scope. Hence,

std::cout << x << std::endl;

is well behaved.

Comments

0

You can't "convert from string to const char*". No such thing exists, because a const char* does not contain characters. It is not a string! It only pointers to some characters somewhere.

In this case, via std::string::c_str(), it points to characters that no longer exist.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.