简体   繁体   中英

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()指向无处,那是无尽的。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM