Please consider the following code:
vector<int> myVector;
myVector.push_back(10);
myVector.erase(myVector.end());
This code compiles and runs fine on Windows (VisualStudio), but results in a segfault on Linux when compiled with g++. Replacing erase with pop_back solves the problem on Linux.
Does anyone know why the behaviour is different on the two platforms, and what behaviour to consider correct.
Thanks in advance!
end()typically returns an invalid position in the array (one beyond the end).pop_back()removes the last item in the vector.If you want to erase, you have to do
erase(end() - 1);hereend() - 1returns an iterator to the last item.erase(end())should invoke UB – which I think is correct…EDIT: as Martin pointed out, before calling
erase(end() - 1), check that the vector is not empty!