Segmentation fault when subtracting elements of Linked List
I am trying to subtract two consecutive nodes and put the result in a new node in front of them. But I get a segmentation error and then the program stops responding.
here LinkList
is the 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++);
}
}
source to share
You cannot dereference a pointer next
in a linked list without first checking its contents. In particular, this expression
q->next->item - q->item
will fail if q->next
- NULL
. You checked q
for NULL
in the header of the loop, but you also need to check q->next
to avoid crashing:
while((q!=NULL) && (q->next != NULL)) {
...
}
source to share