简体   繁体   English

分段故障

[英]Segmentation Fault

I have a base class called IntList, in a IntList.h file.我在 IntList.h 文件中有一个名为 IntList 的基类。 And a inherited class called SortedSet in a SortedSet.h file.以及在 SortedSet.h 文件中称为 SortedSet 的继承类。 The IntList has the following struct :- IntList 具有以下结构:-

struct IntNode
{
    int data;
    IntNode *next;
    IntNode( int data ) : data(data), next(0) {}
};

The following code is a friend function in the SortedSet class.以下代码是 SortedSet 类中的友元函数。 This function returns a SortedSet object that is the union of 2 SortedSet objects, the left and right operands of this binary operator.此函数返回一个 SortedSet 对象,该对象是 2 个 SortedSet 对象的并集,即此二元运算符的左操作数和右操作数。

SortedSet operator|(const SortedSet &lho, const SortedSet &rho)
{
    SortedSet temp;
    IntNode* set1 = lho.head;
    IntNode* set2 = rho.head;

    while(set1->next != 0)
    {
        temp.push_back(set1->data);
        set1 = set1->next;
    }

    delete set1;

    while(set2->next != 0)
    {
        if (temp.in(set2->data) == false)
        {
            temp.push_back(set2->data);
            //cout<<"It isn't in there"<<endl;
        }
        set2 = set2->next;
    }
    delete set2;

    return temp;
}

I am getting a segmentation fault, and I can't seem to fix it.我遇到了分段错误,而且我似乎无法修复它。 Any help would be appreciated.任何帮助,将不胜感激。 Thanks!谢谢!

One obvious error in your code is that you test that set1->next is not null when you should be testing that set1 is not null.代码中的一个明显错误是,当您应该测试set1不为空时,您测试了set1->next不为空。 From the limited information you have posted it is hard to be sure that this is the only problem, but this will almost certainly cause a segmentation fault so I am relatively confident that this is the problem.从您发布的有限信息来看,很难确定这是唯一的问题,但这几乎肯定会导致分段错误,因此我相对相信这是问题所在。

Change your while loops to look like this:将您的 while 循环更改为如下所示:

while(set1 != 0)
{
    temp.push_back(set1->data);
    set1 = set1->next;
}

Then slap yourself in the forehead because this would have been very easy to pick up with a quick application of the debugger.然后拍自己的额头,因为如果快速应用调试器,这很容易上手。

EDIT: You should also remove the delete operations because they will always be acting on a null pointer.编辑:您还应该删除delete操作,因为它们将始终作用于空指针。 It's not clear why you would want to delete just one element of your list anyway so perhaps what you think you are doing doesn't need doing, although with no information about the workings of SortedSet it is hard to know.目前尚不清楚为什么您只想删除列表中的一个元素,所以也许您认为自己正在做的事情不需要做,尽管没有关于SortedSet工作的信息很难知道。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM