The following code fragment compiles and runs without errors and with the expected output:
#include <string> #include <iostream> using namespace std; string getString() { char s[] = "Hello world!"; return s; } int main() { cout << getString() << endl; }
My question is: will this always work? Usually, if you return a C-string that was declared locally, you can run some undefined behavior, but in this case it is a problem, because it is run through the string constructor and (presumably) copied to dynamic memory?
c ++ string
Adrian padin
source share