Devashish Raverkar
Devashish Raverkar

Reputation: 75

segmentation fault in subtracting Linked List elements

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

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

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

Related Questions