Sitesh
Sitesh

Reputation: 1878

Undefined behavior of std::string when c_str() used

The following code example behavior is undefined..

char * getName()
{
   std::string name("ABCXYZ");
   return name.c_str();
}

This is because name goes out of scope. But I wanted to understand how it is different when we return a std::string and does not it produce undefined behavior ?

Upvotes: 0

Views: 290

Answers (2)

David Schwartz
David Schwartz

Reputation: 182761

When you return a value, the value is safely returned to the caller. That's what the return statement does.

In the case where you call c_str, the value you're returning is a pointer into the string. Once the string is destroyed, that pointer now points to nothing in particular. The value is safely returned, it's just that there's nothing you can do with it safely.

The value of a string is the contents of the string. So in that case, it is the contents of the string that gets passed to the caller. One could say that the primary purpose of the std::string class is to provide an object whose value is the contents of a string.

Upvotes: 5

BiagioF
BiagioF

Reputation: 9705

Simply because return instruction copies or moves (see C++11) the object returned.

With this code:

std::string getName() {
   std::string name("ABCXYZ");
   return name;
}

the string name will be copied and returned to the caller.

With your code, return will make a copy of a pointer (because your function returns a pointer), not of the pointed object. That'll produce an UB.

Upvotes: 1

Related Questions