开发者

C++ std::vector segfault when using erase(), ok when using pop_back() with g++

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); here end() - 1 returns 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!


end() points to nowhere, that is beyond the end.


myVector.end() does not point to the last element of the vector. It points past the last element of the vector. I am not sure, though, if this qualifies as undefined behavior (if it does, then it is reasonable that Windows and Linux behave differently).


myVector.end() gives you an iterator to right after the last element in your vector. As there isn't anything there, calling erase on it doesn't make much sense.

I am curious to find out exactly what Visual Studio is doing when you call that though. Run some tests to see if it is actually erasing the 10 from your vector, or if it is just gracefully ignoring your incorrect request.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜