I have the following code:
std::string getString() {
std::string str("hello");
return str;
}
int main() {
const char* cStr = getString().c_str();
std::cout << cStr << std::endl; // this prints garbage
}
What I thought would happen is that getString() would return a copy of str (getString() returns by value); thus, the copy of str would stay "alive" in main() until main() returns. This would make cStr point to a valid memory location: the underlying char[] or char* (or whatever) of the copy of str returned by getString() which, remains in main().
However, this is obviously not the case, as the program outputs garbage. So, the question is, when is str destroyed, and why?