Reputation: 75
I m trying to subtract two consecutive nodes and put the result in a new node before them. But i am getting segmentation fault and then program stops responding.
here LinkList
is a structure.
void subtract_node(LinkList **p)
{
LinkList *q,*temp=NULL,*r;
int i=0;
q=r=*p;
temp=(LinkList*)malloc(sizeof(LinkList));
while(q!=NULL)
{
temp->item=q->next->item-q->item;
temp->next=q;
if(i==0)
{
*p=r=temp;
r=r->next->next;
q=q->next->next;
}
else
{
r->next=temp;
temp=r;
r=r->next->next;
q=q->next->next;
}
printf("%d",i++);
}
}
Upvotes: 4
Views: 380
Reputation: 726609
You cannot dereference the next
pointer in a linked list without null-checking its content first. Specifically, this expression
q->next->item - q->item
will fail when q->next
is NULL
. You did check q
for NULL
in the header of the loop, but you also need to check q->next
to avoid the crash:
while((q!=NULL) && (q->next != NULL)) {
...
}
Upvotes: 1