Visual C++ 中 std::vector::erase() 中的分段错误 [英] Segmentation fault in std::vector::erase() in Visual C++

查看:44
本文介绍了Visual C++ 中 std::vector::erase() 中的分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 std::vector 的擦除函数中遇到了分段错误,这让我发疯了.我有以下代码:

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;
  }   
}

在 lIds.erase(it2) 中,出现分段错误.更准确地说,我在 _Orphan_range(可以在 c:\Program Files\Microsoft Visual Studio 10.0\VC\include\vector 中找到)中得到一个从擦除调用的分段错误.但我不知道为什么.向量和迭代器看起来没问题.但是在_Orphan_range 中,出现了完全错误的情况.尽管我的向量只包含一项,但其中的 while 循环执行了 3 次.在第三次运行中,变量 _Pnext 被破坏.

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!

大卫

不幸的是(或者幸运的是),上面的例子是独立运行的.但在我的大型软件项目中,它不起作用.

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

有人知道失败的函数_Orphan_range 是为了什么而执行的吗?

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

推荐答案

从 std::vector 中擦除会使迭代器失效.参见 STL vector::erase因此,在第一次调用擦除后 it2 无效.唉,检查(it2 != lIds.end())"不会是真的.

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.

将您的代码更改为:

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

这篇关于Visual C++ 中 std::vector::erase() 中的分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆