Segmentation fault in std::vector::erase() in Visual C++

╄→гoц情女王★ 提交于 2021-01-28 08:28:34

问题


I am having a segmentation fault in the erase function of std::vector that is driving me crazy. Am having the following code:

std::map<uint32_t, std::vector<boost::uuids::uuid> >::iterator it
    = theAs.find(lSomeUint32);
if (it != theAs.end()) {
  std::vector<boost::uuids::uuid>& lIds = it->second; // vector contains one entry
  std::vector<boost::uuids::uuid>::iterator it2 = lIds.begin();
  while (it2 != lIds.end()) {
    if (*it2 == lSomeUuid) {
      lIds.erase(it2);
      break;
    }   
    ++it2;
  }   
}

In lIds.erase(it2), I get a segmentation fault. More precisely, I get a segmentation fault in _Orphan_range (can be found in c:\Program Files\Microsoft Visual Studio 10.0\VC\include\vector) that is called from erase. But I have no clue why. The vector and the iterator look ok. But in _Orphan_range, something goes completely wrong. The while loop in there is executed three time although my vector contains one item only. In the third run, the variable _Pnext gets broken.

Does someone have an idea? That would be awesome!

David


Unfortunately (or maybe fortunately), the example above executed standalone works. But inside my big software project, it doesn't work.

Does someone know what the failing function _Orphan_range is executed for?


回答1:


Erasing from std::vector invalidates iterators. see STL vector::erase Therefore it2 is invalid after the first call to erase. Alas the check "(it2 != lIds.end()) " will not be true.

change your code to:

if (*it2 == lSomeUuid) {
  it2 = lIds.erase(it2);
  break;
}  



回答2:


You compare with wrong end iterator.

std::vector<boost::uuids::uuid>::iterator it2 = lIds.begin();
while (it2 != pIds.end()) {

Note lIds and pIds. Try to use more letters in your variables names and don't use hungarian notation. You'd caught Ids_ptr almost instantly.




回答3:


Isn't your

 "theAs.find(lSomeUint32);"

returning the index position rather than the Map::iterator? I'm not sure about this. Can you check it out? The find() function returns the position of the lSomeUint32 in theAs and would return the position of that lSomeUint32 in the string(if it is present). I suppose that is the reason why your erase function is throwing an error. It is not able to erase a data that is not present or that is not in the scope of your program.

Even otherwise if your find() returns the map object I would, in addition to that put a simple if structure to check whether that particular find() returns any object or is NULL just to make sure that the iterator is assigned a value before being operated.

Just a suggestion.



来源:https://stackoverflow.com/questions/7516145/segmentation-fault-in-stdvectorerase-in-visual-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!