简体   繁体   中英

Segmentation Fault

I have a base class called IntList, in a IntList.h file. And a inherited class called SortedSet in a SortedSet.h file. The IntList has the following struct :-

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

The following code is a friend function in the SortedSet class. This function returns a SortedSet object that is the union of 2 SortedSet objects, the left and right operands of this binary operator.

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. 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(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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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