-1

Here is my code that deletes the no of list items from last.I trying to implement the linked list concept.

void del(list** head,int da,int n) {  //da-for no of elements to be   
    list *l1;                         //deleted from end.
    int n1 = n-da;                    //n-for total no of elements in list 
    if (n1 == 0)
        *head = NULL;
    else {
        l1 = *head;
        n1 = n1-1;
        while(n1) {
            l1 = l1->next;
            n1--;
        }
        l1->next=NULL;
     }
}

after including this code I am getting SIGSEGV error. What does it mean? Kindly help me with this code. As I have started learning data structures recently.I dont have that much programming experience but I know some basics in C.

  • Please double check what error exactly you get and quote whatever it is completly and verbatim. Also please do some basic debugging to narrow down as much as possible where you get the error. https://stackoverflow.com/questions/2069367/how-to-debug-using-gdbhttps://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – Yunnosch Sep 25 '17 at 16:42
  • Your error is in the function `del`. What is the meaning if `da` and `n`? Should the elements from indices `da` to `n` be deleted? – M Oehm Sep 25 '17 at 17:18

2 Answers2

1

If you're question is "What is SIGSEGV?" it's the error signal for a Segmentation Fault. Now if you're wondering what's causing it, it's your void del(list** head,int da,int n) function causing undefined behavior when da < n because it causes a logical error inducing a infinite loop:

int n1 = n - da; // Assume n < da

...

while(n1) { // n would be 0< therefor: n1 will never equal 0 causing infinite loop
    l1 = l1->next;
    n1--;
}

A few solutions if you're trying to delete n elements from the back of the linked list:

1. Backwards iteration

Iterate to the tail of the linked list or when list->next == null and then iterating backwards each iteration deleting the node being passed until n nodes have been removed

2. Parent class storing size of the linked list

Another method for this is to have a class linked link that stores the head node, the tail node and the size of the linked list. And then either iterate from the tail of the list deleting n O(N) nodes or iterating to length - n and then begin deleting until you've reached the tail.

Community
  • 1
  • 1
0

I think you're probably getting the segfault when you call delete with too large a value for n1. Your loop in this case:

while(n1) {
  l1 = l1->next;
  n1--;
}

will go too far and access *l1 where l1 == NULL. I do not follow what your del function is supposed to be doing exactly, but this is where your segfault is coming from. If you remove the call to del from main you get no such issue.

0x11
  • 173
  • 8