0

I want to add two polynomials using linked lists. But after entering the second polynomial in 2nd linked list i'm getting a segmentation fault.

when i tried to print the polynomial 1 the powers remain 1 itself but aren't incrementing. Was trying for all possible errors , so code might be little clumsy.

 #include<bits/stdc++.h>
 using namespace std;
 struct node{
  int coef;
  int po;
  node *next;
 }*start1=NULL,*go,*go2,*start2=NULL;
int main()
{
int d1,d2;
cout<<"Enter degree of poly 1 :";
cin>>d1;
cout<<"Enter degree of poly 2 :";
cin>>d2;
int i,c,p;
cout<<"Polynomial 1:" ;
for(i=0;i<=d1;i++)
{   p=1;

    cout<<"Enter coeff of po  "<<i<<" : " ;
    cin>>c;
    node *temp=new node;

    temp->po=p;
    p=p+1;
    temp->coef=c;
    temp->next=NULL;
    go=start1;
    if(start1==NULL)
    {
        start1=temp;
        continue;
    }
    while ((go->next)!=NULL)
    {
        go=go->next;
    }
    go->next=temp;
    p=p+1;
}
cout<<"Polynomial 2 :";
for(i=0;i<=d2;i++)
{   p=1;
    cout<<"Enter coeff of po "<<i<<" :";
    cin>>c;
    node *temp2=new node;
    temp2->po=p;
    temp2->coef=c;
    temp2->next=NULL;
    go2=start2;
    if(start2==NULL)
    {
        start2=temp2;
        continue;
    }
    while ((go2->next)!=NULL)
    {
        go2=go2->next;
        cout<<"kk";
    }

    go2->next=temp2;
    p=p+1;
}       
go=start1;
while(go!=NULL)
{
    go2=start2;
    while(go2->next !=NULL)
    {
        if((go->po)==(go2->po))
        {
            go->coef = go->coef + go2->coef;
        }
        go2=go2->next;
    }
    go=go->next;
}
    go=start1;
cout<<"Resultant Polynomial : ";
for(i=0;i<=d1;i++)
{
    cout<<go->coef<<"^"<<i+1<<" + ";
    go=go->next;
}

i expected the powers to be increasing but it is left as 1 and im getting a segmentation fault

Uday P
  • 71
  • 1
  • 5

1 Answers1

0

The reason why the program crashes is because here:

cout << "Resultant Polynomial : ";
for (i = 0; i <= d1; i++)
{
    cout << go->coef << "^" << i + 1 << " + ";

go is a nullpointer. This is because before this snippet, you have this loop:

while (go != NULL)
    { ... }

So when this loop ends, go is a nullpointer as the loop doesn't end otherwise (it doesn't break or terminate otherwise). Did you mean to set go to a different initial value after this loop?


On an unrelated note, please read Why should I not #include <bits/stdc++.h>? and Why is "using namespace std;" considered bad practice?

Blaze
  • 16,736
  • 2
  • 25
  • 44
  • Sorry I missed a line there... Is the problem same now? Because I I'm getting the same error – Uday P Aug 28 '19 at 07:52
  • I don't know what you intended to put there, but if I put `go = start1;` before the `cout << "Resultant Polynomial : ";` for instance, the segementation fault is gone and the program terminates properly. – Blaze Aug 28 '19 at 07:55