-2

for the follwoing program segment:

std::vector<int*> v;
{
    int a=5000;
    int *aa =&a;
    vv.push_back(aa);
    cout<<"\n"<<*(v[0]);
}
cout<<"\n"<<*(v[0]);

output:

5000
5000

my doubt here if inserting pointer to an vector ,vector should have address and while acessing it from outside of local block it should not print the elemet becuase "a" has local scope. here oject of that pointer has local scope still its accessible from outside of the scope. plese help. thanks

Marco A.
  • 43,032
  • 26
  • 132
  • 246
  • 3
    It's undefined behavior – Anton Savin Oct 17 '14 at 14:08
  • Accessing a stale pointer. See [this answer](http://stackoverflow.com/a/6445794/1782465). – Angew is no longer proud of SO Oct 17 '14 at 14:10
  • "Stale pointer". I like this expression. – Quentin Oct 17 '14 at 14:11
  • pro tip: don't use naked raw pointers, especially in C++, you have all the tools that you need to avoid them and express a better semantic, you also get smart pointers in the event that you really really really need one of those things . – user2485710 Oct 17 '14 at 14:15
  • C++ is not a managed language. Don't expect the compiler or the run-time to recognize whether a pointer is still valid. That's the coder's job. – Darryl Oct 17 '14 at 14:28
  • `it should not print the elemet because ...` So what do you think *is* supposed to happen when this occurs? If you don't know, then that's the point of "undefined behavior". No one can guarantee what should happen, even the language can't guarantee what happens. – PaulMcKenzie Oct 17 '14 at 14:30

1 Answers1

5

The vector grabs a copy of the pointer, it is perfectly valid to use it.

The problem is with the address where the pointer points: you're accessing out-of-scope stack memory which could have been recycled (i.e. used). You have no guarantee on this access and thus invoking undefined behavior.

Marco A.
  • 43,032
  • 26
  • 132
  • 246