Reputation: 79
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 :)
Upvotes: 2
Views: 817
Reputation: 118292
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.
Upvotes: 1
Reputation: 341
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)
Upvotes: 4