问题
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 next
and 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