-
Linked list trouble
I'm getting a seg fault and I can't work out why.
Code:
int add_node(void){
struct list *temp;
// Go to end of list
current = &head;
if(current){
while(current){
current = current->next;
}
}
else return 1;
// Allocate memory
temp = malloc(sizeof(struct list));
if(!temp)
return 1;
temp->next = NULL;
//current->next = temp; /* This line gives me the seg fault */
return 0;
}
It looks good to me but it's late and I can't work out why this isn't working. If more code is needed, just ask.
[edit]
nevermind, I fixed it. (I seem to do this a lot dont I?)
-
current is null
The reason for your error is because you are looping through current while there is a current. Therefore, it will be null after the loop finishes. You need to keep a pointer to the last thing prior to it going null. Lastly, you should check that current is valid prior to attempting an assignment.
-
penney is right. If you want to go to the end of the list you must use loop like this:
Code:
while ( current->next )
{
current = current->next;
}
What are you trying is to dereference null pointer and that is seg fault!