Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scopes and c++ pointers

Tags:

c++

scope

I have the following code:

using namespace std;
vector<string*> v;
{
  string s = "hello";
  v.push_back(&s);
}
{
  string ss = "goodbye";
  v.push_back(&ss);
}

cout << v.at(0)->c_str() << endl;
cout << v.at(1)->c_str() << endl;

which prints

goodbye
goodbye

if I remove the scope parenthesis the code will print

hello
goodbye

What exactly happens when I leave the first scope, that the pointer to the first string now points to the second one?

like image 676
Bg1987 Avatar asked Jan 09 '12 15:01

Bg1987


1 Answers

The stored pointers become dangling pointers after the scope and any attempt to read what they point to yields undefined behavior.

like image 168
Sebastian Mach Avatar answered Oct 12 '22 19:10

Sebastian Mach