Segmentation Fault

I am running into a segmentation fault when the program is ran. Does anyone know why this is happening? Thank you in advanced.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include<stdio.h>
#include<stdlib.h>
//polynomials:  as we go through the list, the exponents decrease

struct term {
  double coef;
  int exp;   // exponent is >=0
  struct term *next;
};

class Poly {
private:
  struct term *head;
public:
  Poly() {
    printf("empty constructor\n");
    head=0;
  }

  Poly(Poly const &p)  //copy constructor
  {
    head=0;
    printf("copy constructor\n");
    for(term *curr = p.head; curr!=0; curr=curr->next) {
      addTerm(curr->coef, curr->exp);
    }
  }

  Poly& operator=(const Poly &p) {
     for(term *curr=head; curr!=0; ) {
        term *prev = curr;
        curr = curr->next;
        delete prev;
     }
  }

  void addTerm(double coef, int exp) ;

  //multiplication of two polys
  Poly operator*(Poly &p) {
    printf("my mul not Sternfeld's\n");
    Poly result;
    return result;
  }

  //addition of two polys
  Poly operator+(Poly &p) {
    Poly ans;
  }

  void print() {
    if (head==0) {
      printf("0\n");
      return;
    }
    for(struct term *curr=head; curr!=0; curr= curr->next)
      if (curr->exp==0)
         printf("%+f", curr->coef);
      else if (curr->exp==1)
        printf(" %+fx", curr->coef);
      else
        printf(" %+fx^%d", curr->coef, curr->exp);
    printf("\n");
  }
};



void Poly::addTerm(double coef, int exp){
  struct term *NP;
  if(head){
  NP=(struct term *)malloc(sizeof(struct term));
  NP->coef=coef;
  NP->exp=exp;
  NP=NP->next;
  NP->next=0;
 }else
 {
  NP->coef=coef;
  NP->exp=exp;
  NP->next=(struct term*)malloc(sizeof(struct term));
  NP->next=0;
 }
}

int main(){
 Poly p;
 p.addTerm(3,5);
 p.print();
 }

There seems to be quite a few problems with the addTerm function.

You always need to allocate a new term. At the moment you only do it if the head pointer is not null.

Line 75 and 81 doesn't seem right. You should probably just remove these lines.

You need to update the head pointer. If you want the new term to be added to the end of the list you only need to update head when it's null but then you need to traverse the list so that you set the next pointer of the previously last term to point to the new term. If you want the new term at the front of the list you'll have to update the head pointer each time and you also need to set the next pointer of the new term to point to the term that was previously pointed to by head.

You also need to make sure to add a return statement when defining the + and = operators.
Last edited on
In addTerm(...): if head is 0 NP remains uninitialized (which cause the crash) and head remains 0.

You shouldn't use malloc(...) in C++ code and prepending term with struct is unnecessary.
Less C-like and more C++-like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <map>
#include <iomanip>

//polynomials:
class Poly
{
    private:

        // key expnent, mapped value: coefficient
        // std::greater<>: as we go through the list, the exponents decrease
        std::map< unsigned int, double, std::greater<> > terms ;

    public:

    Poly( std::initializer_list< std::pair< double, unsigned int > > ilist = {} )
    { for( const auto& pair : ilist ) addTerm( pair.first, pair.second ) ; }

    void addTerm( double coef, int exp ) { terms[exp] += coef ; }

    Poly& operator+= ( const Poly& that )
    {
        for( const auto& pair : that.terms ) addTerm( pair.second, pair.first ) ;
        return *this ;
    }

    friend Poly operator+ ( Poly a, const Poly& b ) { return a += b ; }

    friend std::ostream& operator<< ( std::ostream& stm, const Poly& p )
    {
        if( p.terms.empty() ) return stm << "0 " ;

        static const auto print_term = [&stm]( auto iter )
        {
            stm << std::setw(7) << iter->second ;
            if( iter->first == 1 ) stm << "x " ;
            else if( iter->first > 1 ) stm << "x^" << iter->first << ' ' ;
        };

        // print the first term
        auto iter = p.terms.begin() ;
        stm << std::fixed << std::setprecision(2) << std::noshowpos << std::right ;
        print_term(iter) ;

        // print the remaining terms
        stm << std::showpos << std::internal ;
        for( ++iter ; iter != p.terms.end() ; ++iter ) print_term(iter) ;

        return stm ;
    }
};

int main()
{
    Poly a( { {3.0,5}, {2.1,2}, {1.6,5}, {7.0,0}, {-22.0,1}, {3.6,2} } );

    Poly b( { {-2.8,5}, {9.3,4}, {-17.2,0}, {-1.6,7} } );

    std::cout << "a: " << a << '\n'
              << "b: " << b << '\n'
              << "a+b: " << a+b << '\n' ;
}

http://coliru.stacked-crooked.com/a/be0fc3d5d467cbd5
also if you want to use C headers in C++

 
#include <cstdio> //add a 'c' in front of every single C headers and remove ".h" 
Topic archived. No new replies allowed.