0

The code here is simple:

int main() {
 vector<string> v;
 v.push_back("hello");
 string& x = v[0];
 v.push_back("world");
 cout << x << endl;
 return 0;
}

Why is there a runtime error? Please explain it in detail.

asked Mar 23, 2017 at 8:48
1
  • 6
    According to the documentation of std::vector::push_back (did you even look at it?): If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is invalidated. (emphasis mine) Commented Mar 23, 2017 at 8:51

1 Answer 1

13

Have a read through a reference : std::vector::push_back. Specifically the part that says :

If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is invalidated.

When you pushed back the second string into the vector, it appears it had to re-allocate memory, because there wasn't enough capacity for the second string. This re-allocation moved the entire vector data elsewhere in memory - including the first string you pushed into it. So the reference to that first string became a dangling reference, and de-referencing it has undefined behavior.

answered Mar 23, 2017 at 8:51
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.