+ 1

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,&degree); 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,&degree); 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; }

7th Dec 2019, 4:18 PM
Tanmoy
6 ответов
+ 3
why not put it in code playground and link it here, it will be easy to debug that way, looks rough to me now
7th Dec 2019, 4:58 PM
✳AsterisK✳
✳AsterisK✳ - avatar
+ 3
Agreed with ✳AsterisK✳ ! Would be glad to help but it is hard this way :)
7th Dec 2019, 6:00 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 3
Oh, I shouldn't have spoken too quickly. I think the error is because display modify the value of head1 so p is NULL Use a simple pointer for this one instead of a double and it should work (at least for this error ^^)
7th Dec 2019, 7:20 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 2
✳AsterisK✳ is right. Segmentation fault error, what a classic :)
7th Dec 2019, 6:21 PM
Gonçalo Magalhaes
Gonçalo Magalhaes - avatar
+ 2
Yeah I got it! Thanks for the help! And please forgive me for not putting the code in playground.I'll take care of this the next time.
8th Dec 2019, 5:50 PM
Tanmoy
0
display(&head3);*/ printf("%d",p->coe); getch(); return 0; } <This portion got omitted from the question,so i'm writing it here.>
7th Dec 2019, 4:20 PM
Tanmoy