Why does calling std :: vector :: back () crash my program

I'm not sure what happened to this code:

std::vector<int> myVector(0); if (myVector.back() == 12) myVector.push_back(12); 

It seems that callback () on an empty vector resets the program.

I do not understand why it is crumbling? Do I need to check the length of a vector before calling back() ? or is it possible that this is a mistake?

The documentation says that if the vector is empty, it returns undefined.

+6
source share
2 answers

Do I need to check the length of the vector before calling the function ()?

In a word: yes. This is your mistake, your vector is empty, so there is no back element.

The documentation should indicate (if it says anything at all) that calling back() on an empty vector causes undefined behavior, and not that it returns undefined.

+13
source

C ++ 11 reports the following:

23.3.2.8/3

It is not possible to call the call front () or back () function on an array of zero size.

Since the behavior is undefined, anything can happen. You are fortunate enough to fail.

+5
source

Source: https://habr.com/ru/post/906380/


All Articles