I am trying to implement polynomial addition using linked list. I have only coded a small part of it where i accept the input into first polynomial and while i was testing the code it kept throwing a segmentation fault error. I have sprinkled some random printf statements to try to debug the code.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
struct node{
struct node* next;
int coeff, power;
};
struct node* createNode(){
struct node *temp;
temp=(struct node*)malloc(sizeof(struct node));
temp->next = NULL;
return temp;
}
struct node* poly1,poly2,poly3;
void createList(struct node* head){
int ch=0;
struct node* temp;
struct node* newNode = createNode();
head=NULL;
temp=NULL;
while(ch!=-1){
printf("Enter coefficient and power");
scanf("%d",&newNode->coeff);
scanf("%d",&newNode->power);
if( head ==NULL){
printf("123123123");
temp = newNode;
head = newNode;
printf("bbbbbb");
}else{
printf("aaaaaaaa");
temp->next = newNode;
temp = newNode;
}
printf("Enter -1 to exit");
scanf("%d",&ch);
printf("9999");
}
printf("1");
}
void display(struct node* head)
{
struct node *temp;
temp=head;
if(temp==NULL)
printf("LL not present");
else
{
while(temp!=NULL)
{
printf("%dx^%d ",temp->coeff,temp->power);
temp=temp->next;
}
}
}
void main(){
printf("Enter the data for the first polynomial\n");
createList(poly1);
printf("%d",poly1->coeff);
display(poly1);
}
This is the output i am getting for it-
Enter the data for the first polynomial Enter coefficient and power3 2 123123123bbbbbbEnter -1 to exit9 9999Enter coefficient and power 1 1 1 1 aaaaaaaaEnter -1 to exit-1 Segmentation fault
Interestingly when i change the second last line of my while loop from
scanf("%d",&ch);
to ch=-1; the output that i get has none of the random printf i added to debug :
Enter the data for the first polynomial Enter coefficient and power3 2 Segmentation fault
I dont understand what the difference is between both of these cases. Also whats the issue with segmentation fault being thrown around?