#include <iostream>
#include <string>
using namespace std;
struct Bar {
string str;
};
struct Foo {
Bar* bar;
};
int main() {
Foo foo;
if (true) {
Bar bar;
bar.str = "test";
foo.bar = &bar; // version 1
// *(foo.bar) = bar; // version 2
}
cout << foo.bar->str << endl;
return 0;
}
The above program prints nothing. My understanding is that when the if statement exits, variable bar which was allocated on the stack doesn't exist anymore and foo.bar holds a pointer to a undefined memory location in the stack. What I do not understand is that when I change the line to the currently commented-out line (marked with version 2). It gives me segmentation fault. Can anyone help me understand why that's the case? Also, if I want to print "test" for this program, what code changes I have to make?