Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the call to std::vector::back() crash my program

I am not sure what's wrong with this code :

std::vector<int> myVector(0);

if (myVector.back() == 12)
    myVector.push_back(12);

It seems that calling back() on an empty vector crashes the program.

I don't understand why it's crashing? Do we need to check the length of the vector before calling back()? or is possible that it's a bug?

The documentation says, that if the vector is empty it return an undefined value.

like image 856
MBen Avatar asked Jan 19 '12 10:01

MBen


2 Answers

do we need to check the length of the vector before calling back() ?

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

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

like image 194
CB Bailey Avatar answered Oct 12 '22 13:10

CB Bailey


c++11 standard tells this:

23.3.2.8 / 3

The effect of calling front() or back() for a zero-sized array is undefined.

Since the behaviour is undefined, anything can happen. You were lucky to get a crash.

like image 34
BЈовић Avatar answered Oct 12 '22 12:10

BЈовић