-1

I know that a dangling handle is a pointer or reference to invalid data. And I experiment with string and vector, below is my code with string:

    char *p = NULL;
    {       
        string s;
        s.push_back('a');
        s.push_back('b');
        p = &s[0];
    } 
    cout << *p << endl;

and the result is 'a'. It surprised me, shouldn't p be a dangling pointer? And I think that the object s should have been destructed, why can p still point to the valid content?
And I do another experiment with vector by just replacing the "string" with "vector" in the code above, and this time print nothing. So what does this mean? Is there any difference that string and vector organize their members?

Philip Zhang
  • 627
  • 8
  • 17
  • 1
    The object *was* destructed, and the internal buffer deallocated. However there is no requirement for the buffer to be zeroed out or anything. That's why it is undefined behavior to access a dangling pointer. – StoryTeller - Unslander Monica Jan 26 '14 at 11:48
  • 3
    Just because it prints 'a' doesn't mean it's correct. It's undefined behavior. Since nothing else happens between `s` going out of scope and `p` being printed, it happens to "work". – John3136 Jan 26 '14 at 11:49
  • 1
    Yes - at the time that you print it, p is pointing to the place where s **was** stored. The value just might happen to still be at that location, but it is not guaranteed. – GreenAsJade Jan 26 '14 at 11:49
  • 1
    That's not how logic works. – Kerrek SB Jan 26 '14 at 12:01

2 Answers2

2

You are invoking undefined behaviour, so anything can happen. In your case it just happens that the memory hasn’t been overwritten yet. It could also just segfault, wipe your harddrive or awaken the nasal demons.

1

Traffic laws say that if you wait for a green light, you are guaranteed to be able to cross the road safely.

You are complaining that not everyone who crosses at a red light is instantly crushed by a truck.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • And: Are *you* willing to pay for a fleet of trucks out of your own pocket to make sure jaywalkers are promptly crushed? – Kerrek SB Jan 26 '14 at 12:06