【发布时间】:2019-08-15 08:56:18
【问题描述】:
下面的代码抛出 heap-use-after-free 错误。
#include <iostream>
int main()
{
unordered_map<int, vector<int>::iterator> mp;
vector<int> num;
auto insert = [&](int n)
{
if (mp.count(n) != 0)
return false;
num.push_back(n);
mp[n] = prev(num.end());
return true;
};
insert(1);
insert(2);
insert(3);
for (auto n : num)
cout << n << endl;
cout << endl;
for (auto m : mp)
{
cout << m.first << " -> ";
cout << distance(num.begin(), m.second) << endl;
// cout << *m.second << endl;
}
return 0;
}
上面代码的输出是
1
2
3
3 -> 2
1 -> -16
2 -> -7
如果我尝试访问*m.second,它显然会崩溃。
为什么这里的迭代器值似乎损坏了?
我尝试用列表替换向量,上面的代码工作正常。我想知道这是否与矢量如何在“push_back”上扩展有关。我已经尝试过其他方法来让迭代器到达向量的最后一个元素,但结果并不相同。
【问题讨论】:
标签: c++11 iterator stdvector stdlist