Getting Segmentation fault error
I was trying to add to polynomials by using linked lists but couldn't understand the reason of segmentation fault at this line <printf("%d",p->coe);> I understand that this error is shown when we try to access an illegal memory location but in this case i am not able to understand the cause. Please Help. Program below: #include <stdio.h> #include <malloc.h> #include <conio.h> struct node { int coe; int deg; struct node *next; }; typedef struct node Node; Node *newnode() { Node *p = (Node*)malloc((sizeof(Node))); p->next = NULL; return p; } Node *head1 = NULL,*head2 = NULL,*head3 = NULL; void create(Node **p,int coeff,int degree) { Node *temp = newnode(); temp->coe = coeff; temp->deg = degree; Node *q; if(*p==NULL) { *p = temp; } else { q = *p; while(q->next!=NULL) { q = q->next; } q->next = temp; temp->next = NULL; } } void display(Node **p) { while(*p!=NULL) { printf("%dx^%d+",(*p)->coe,(*p)->deg); *p = (*p)->next; } } int main() { int coeff,degree; printf("Enter first polynomial in the format <coefficient> <degree>:"); scanf("%d %d",&coeff,°ree); create(&head1,coeff,degree); while(degree>0) { degree--; printf("\nEnter coeff. for x^%d:",degree); scanf("%d",&coeff); create(&head1,coeff,degree); } printf("\nEnter second polynomial in the format <coefficient> <degree>:"); scanf("%d %d",&coeff,°ree); create(&head2,coeff,degree); while(degree>0) { degree--; printf("\nEnter coeff. for x^%d:",degree); scanf("%d",&coeff); create(&head2,coeff,degree); } display(&head1); display(&head2); printf("-------------\n"); Node *p = head1,*q = head2; /*while(p->next!=NULL) { if(p->deg == q->deg) { create(&head3,p->coe+q->coe,p->deg); } else if(p->deg>q->deg) { create(&head3,p->coe,p->deg); create(&head3,q->coe,q->deg); } else { create(&head3,q->coe,q->deg); create(&head3,p->coe,p->deg); } p = p->next; q = q->next; }