简体   繁体   中英

Linked List Segmentation Fault C

I am learning linked lists in C and I am having a problem with my delete function keeps giving me a segmentation fault. I do not know what is wrong with the code.

void delete(int d)
{
    struct list * current1 = head; 
    struct list * current2;

    if (len() == 0)
    { //prtError("empty");
        exit(0);
    }
    if (head -> data == d)
    { 
        head = head -> next;
    }

    //Check if last node contains element
    while (current1->next->next != NULL)
        current1 = current1->next;
    if(current1->next->data == d)
            current1->next == NULL; 


    current1 = head; //move current1 back to front */

    while(current1 != NULL && (current1->next->data != d))
        current1 = current1 -> next; 


    current2 = current1 -> next;
    current1 -> next = current2 -> next; 
}

From a quick glimpse:

Lets say there are 100 structs ranging from 1~99.
The 100th would be (probably) NULL.


while(current1 != NULL && (current1->next->data != d))

When the above code reaches the 99th struct. You execute 2 checks.

1) Check if the 99th is not NULL .. returns true
2) Check if the 100ths data is different than d

But there's no 100th struct.
This results to undefined behaviour which COULD and probably WOULD lead to a segfault.

This is wrong in so many ways:

1)

while (current1->next->next != NULL)

If the list has only one element:

current1 = head;
current1->next = NULL; 
current1->next->next = Seg Fault

2)
If you're going to look if the last element has the provided data make sure you return from the function once you have found it and also free the memory for it:

while(current1->next->next != NULL)
    current1 = current1->next;
if(current1->next->data == d){
        free(current->next);
        current1->next == NULL;
        return; 
}


3)
If you search as above if the last element has your data (although a pointless search; no need to do it separately) you eliminate an error case from the code bellow. But you will still have the situation when your data cannot be found in the list and current1 is positioned on the last element (so != NULL ) but current1->next->data != d with crash your program. This will happen if you don't return from the function at 2).

current1 = head; //move current1 back to front */
while(current1 != NULL && (current1->next->data != d))
    current1 = current1 -> next; 


4)
Free memory for the deleted node:

current2 = current1 -> next;
current1 -> next = current2 -> next; 
free(current2);

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