-2

I am running following simple program in C++ program:

 #include <iostream>
 using namespace std;
 string& ShowString()
 {
     string s1 = "abcd";
     return s1;
 }
 int main()
 {
     string s2 = ShowString();
     cout << s2 << endl;
     return 0;
 }

and the output is: abcd

The problem is that function ShowString returns a reference to a local variable and by the time that program reaches to cout << s2 << endl, s1 should have been destroyed (and also s2). But the output is still correct, which brings me to the conclusion that although s1 no longer exists, its contents in stack memory are still valid (probably until something else overwrites it).

I appreciate if you could let me know whether this conclusion is correct.

Thanks

Pouya
  • 1,871
  • 3
  • 20
  • 25

1 Answers1

2

Because it is an Undefined Behaviour. You can't trust that value.

Sreeraj Chundayil
  • 5,548
  • 3
  • 29
  • 68