Why do I get a segmentation fault?

This information is a basic truth of how memory works. You aren't allowed to reference variables after they are out of scope (and potentially filled with garbage) in C or C++ either.

The same issue has been brought up many times here. The last one was a week ago. Please use the search.