My question is about the following simple code:
#include <iostream>
using namespace std;
const char* call()
{
string str("Hey there.");
return str.c_str();
}
int main()
{
const char* blah = call();
cout << blah << endl;
system("pause");
return 0;
}
Output: "Hey there."
Now, how is it that the memory holding "Hey there." isn't destroyed or causing a memory leak when std::string is destroyed at the end of the method? I'm not a c++ expert but i believe if the string allocated memory holding "Hey there." on the stack, it would be deleted when the string goes out of scope (end of method), and if the string allocated memory on the heap to store "Hey there." then this would cause a memory leak since its clearly not destroying the memory because we are accessing the memory after the string has gone out of scope.
So, how is it that i am able to access the memory blocks pointed to by c_str() without causing a memory leak?
Thank you and much appreciated responses.