Why does this work: returning C string literal from std::string function and calling c_str()

c++, stdstring, temporary-objects, undefined-behavior

Solution

Your analysis is correct. What you have is undefined behaviour. This means pretty much anything can happen. It seems in your case the memory used for the string, although de-allocated, still holds the original contents when you access it. This often happens because the OS does not clear out de-allocated memory. It just marks it as available for future use. This is not something the C++ language has to deal with: it is really an OS implementation detail. As far as C++ is concerned, the catch-all "undefined behaviour" applies.

Problem

We recently had a lecture in college where our professor told us about different things to be careful about when programming in different languages. The following is an example in C++: ``` std::string myFunction() { return "it's me!!"; } int main() { const char* tempString = myFunction().c_str(); char myNewString[100] = "Who is it?? - "; strcat(myNewString, tempString); printf("The string: %s", myNewString); } ``` The idea why this would fail is that `return "it's me!!"` implicitly calls the `std::string` constructor with a `const char[]`. This string gets returned from the function and the function `c_str()` returns a pointer to the data from the `std::string`. Since the string returned from the function is not referenced anywhere, it should be deallocated immediately. However, running this code works without problems. Why is that?

Original source

Related problems