Circular Doubly Linked List - Segmentation fault: 11 [closed]

[亡魂溺海] 提交于 2020-01-07 03:57:14

问题


I'm trying to implement a circular doubly linked list but I keep getting a segmentation fault: 11 error (I believe it's because of the add and delete functions). I have no idea whether my code is even close, but I can't get past this error to test it properly. This is the code I have that I believe is involved:

(Circular_DLList.cc)

void Circular_DLList::add_to_tail(int a)
{
    if (is_empty()) {
        tail = new DLLNode(a);
        tail->next = tail;
    }
    else {
        tail->next = new DLLNode(a, tail->next);
    }
}

int Circular_DLList::delete_from_tail()
{
    if(!is_empty()) 
    {
        int a = tail->info;
        tail = tail->prev;
        tail->next = null;
        return a;
    }
    else
    {
        tail = 0;
    }
    return a;
}

Any help would be fantastic, thanks.


回答1:


One way to find a segmentation fault is by using cout statements throughout your code and compiling and running it. If the cout statement prints something to the console then the segmentation fault happens in a line after the cout statement. Keep doing this to narrow down and locate where the line with the segmentation fault is.




回答2:


There is more than one problem in your code but here is one of them.

When you add the first element, you do:

    tail = new DLLNode(a);
    tail->next = tail;

so you leave prev equal to 0 (BTW: use nullptr instead of 0).

If you then delete the element you do:

    int a = tail->info;
    tail = tail->prev;  // tail becomes 0
    tail->next = null;  // Dereference 0 cause seg fault
    return a;

BTW: Your delete function should also delete the DLLNode ! Just changing pointer values isn't sufficient.

So this leads to 3 changes:

1) When adding new elements make sure to always set both nextand prev

2) Remember to delete the DLLNode created with new

3) In your delete function you need a special case for checking whether the list contains exactly one element, i.e. if (tail == tail->next) { .. delete last element .. set tail equal nullptr}



来源:https://stackoverflow.com/questions/36302247/circular-doubly-linked-list-segmentation-fault-11

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!