c++中列表上的分段错误
Segmentation fault on list in C++
我正在使用一个包含私有列表的类:
class Set
{
private:
list<long long unsigned> ways; //holds tags of addresses
作为类功能的一部分,我正在管理列表中的"方法"中的后进先出:
list<long long unsigned>::iterator it = ways.begin();
while (it!= ways.end()) //looks for the tag in the list
{
if ((*it) == tag) //tag is found in this set. moves the tag to the end of the list
{
ways.erase(it);
ways.push_back(tag);
return true;
}
it++;
}
return false;
:
if (occupied < maxWays) //if the set is not all used up just pushes tag in the end
{
ways.push_back(tag);
occupied++;
return false;
}
else // if used up pops the front member (the least recently used one)
{
ways.pop_front();
ways.push_back(tag);
}
return true;
没有其他内容触及'ways',也没有其他内容擦除'set'类。在开头创建了'set'类的多个实例。
在操作过程中,我得到分割故障
list<long long unsigned>::iterator it = ways.begin();
在长时间运行后发生。试图在这一行之前打印"ways"的地址,这表明在我即将得到分割错误的时候,"ways"的地址发生了巨大的变化。以前每个实例的值都在0x6000xxxxx左右,而这次是0x23。
我不知道是什么原因导致的,请帮助。
可以从列表中删除一个元素,然后对迭代器进行自增,迭代器指向被删除的元素。
您可能需要先转发迭代器,然后删除前面的迭代器,以达到您想要的效果。看到的:你能从std::列表中删除元素而遍历它吗?
EDIT:参见erase()的返回值,以及修改迭代器包的类似操作。http://www.cplusplus.com/reference/list/list/erase/
是否初始化'occupied'和'maxWays' ?如果没有,请参见我们在空列表ways上调用ways.pop_front()时失败的示例。
class Set
{
public:
Set(int max)
{
maxWays = max;
occupied = 10; // Say randomly stored value 10 is more than maxWays = 5
}
bool search(long long tag)
{
list<long long unsigned>::iterator it = ways.begin();
while (it!= ways.end()) {
if ((*it) == tag) {
ways.erase(it);
ways.push_back(tag);
return true;
}
it++;
}
return false;
}
bool add(long long tag)
{
if (occupied < maxWays) {
ways.push_back(tag);
occupied++;
return false;
}
else {
ways.pop_front(); // may fail here
ways.push_back(tag);
}
return true;
}
private:
list<long long unsigned> ways;
int maxWays;
int occupied;
};
int main()
{
Set set(5);
cout << set.add(100) << endl;
return 0;
}
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?
- 动态类的分段错误(家庭作业问题)
- 分段错误 - 读取初始化指针的数组
- 如何摆脱C ++中的分段错误错误?
- 使用 CTYPE 时出现分段错误
- 为什么代码给出分段错误?