简体   繁体   English

链表中的分段错误

[英]Segmentation fault in a linked list

I am trying to make a programme for polynomials. 我正在尝试为多项式编写程序。 I add an element to polynomial using the addTerm function.There appears to be a segfault in the first "else" part of the function. 我使用addTerm函数将一个元素添加到多项式。函数的第一个“ else”部分似乎出现了段错误。

#include <iostream>
#include <math.h>
using namespace std;
class Polynomial{
 protected:
  class Term{
  public:
    int exponent;
    int coefficient;
    Term *next;
    Term(int exp, int coeff,Term *n){
      exponent = exp;
      coefficient = coeff;
      next=n;
    };
    friend class Polynomial;
   };
   Term *head;
 public:
 Polynomial(){
  head=nullptr;
  head->next=nullptr;
 }
 Polynomial(const Polynomial &p){
  head=nullptr;
  Term* curr=p.head;
  while(curr!=nullptr){
    addTerm(curr->exponent,curr->coefficient);
    curr=curr->next;
  }
   }
 ~Polynomial(){
  Term* curr=head;
  while(curr!=nullptr){
    Term* next=curr->next;
    delete curr;
    curr=next;
  }
  head=nullptr;
  };

  Polynomial & operator = (const Polynomial &p){
  Term* curr=head;
  while(curr!=nullptr){
    Term* next=curr->next;
    delete curr;
    curr=next;
  }
  head=nullptr;
  Term* current=p.head;
  while(current!=nullptr){
    addTerm(current->exponent,current->coefficient);
    current=current->next;
  }
  return *this;

};

void addTerm(int expon, int coeff){
  if(head==nullptr){                              //adeia lista
    Term* t=new Term(expon,coeff,nullptr);
    head=t;
    // cout<<t->exponent<<t->coefficient;
  }
  else{
    if(expon>head->exponent){                  
      Term* temp= new Term(expon,coeff,head);
      temp->next=head;
      head=temp;
    }
    else{

     Term* current=head;
      for(current=head;expon!=current->exponent;current=current->next){
        if(current==nullptr) break;
      }
      if(current->exponent==expon){
        current->coefficient=current->coefficient+coeff;
      }
      else{
        current=head;
        Term* prev=head;
        while(expon<current->exponent){

         prev=current;
          current=current->next;
       }
        Term* temp=new Term(expon,coeff,current);
        prev->next=temp;
     }
}
}

The code I run it on is: 我运行它的代码是:

int main(){
 Polynomial p;
 p.addTerm(3,1);
 p.addTerm(2,3);
 }

Your program crashes in the Polynomial constructor which looks like this: 您的程序在多项式构造函数中崩溃,如下所示:

Polynomial() {
  head=nullptr;
  head->next=nullptr;
}

That does not work because you have set "head" to null and then after that you try to access head->next. 那是行不通的,因为您已将“ head”设置为null,然后尝试访问head-> next。

You cannot use head->next when head is null. 如果head为null,则不能使用head-> next。 Trying to do so will lead to a "segmentation fault" crash. 尝试这样做将导致“分段错误”崩溃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM