c++中列表上的分段错误

Segmentation fault on list in C++

本文关键字:分段 错误 列表 c++      更新时间:2023-10-16

我正在使用一个包含私有列表的类:

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