简体   繁体   中英

C segmentation fault linked list

For school I have to implement a pop function to a linked list. But when I run it I get a segmentation fault and I have no idea why... I already debugged it and it points me to *value = current->next; I'm very new to C so I'm sorry if this is a dumb question.

Note: I had to implement much more functions beside pop. So every other function call you see here, is already implemented and works correct.

list.h

int list_pop(struct List* list, int* value);

list.c

int list_pop(struct List* list, int* value)
{
    struct ListNode* curr = list->first;
    struct ListNode* prev;

if (curr == NULL)
    return 0;

while (curr != NULL)
{
    prev = curr;
    curr = curr->next;
}

*value = curr->value;   **Debugger says that in this line there is something wrong.**
prev->next = NULL;
free(curr);
return 1;

Thank you in advance, also it would be very cool if someone could tell me if this pop function is correct :)

while (current != NULL)
{
    previous = current;
    current = current->next;
}

*value = current->value; 

At the end of your while loop, current is NULL.

You want to iterate while there is a next element. Therefore, you should replace it by

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

So this while loop will terminate when current is NULL. Wonderful! Now, what's the next thing that's going to happen?

*value = current->value;

Well, current is now NULL. Dereferencing the NULL pointer will make the debugger very sad.

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