Search code examples
c++scientific-computing

Segmentation error while calculating partial derivative


I am trying to calculate the partial derivatives of the function f(x,y)=x+y w.r.t x and y at the point (3, 2). I wrote the code but it is giving me an error called Segmentation fault (core dumped). I don't what that is. Can anyone please point out what is wrong in this?

#include<iostream>
#include<cmath>
#include<vector>
using namespace std;

class Der{

private:
    double f;  // function value at x
    vector <double> df; // derivative of function at x
    
public:
    Der();
    Der(vector <double>* v);
    Der operator+(Der); // f + g
    
    void print();
    
};

Der :: Der(){}

Der :: Der(vector <double>* v){
    this->f = v->at(0);
    for(int i=1; i < v->size(); i++){
        this -> df[i-1] = v->at(i);
    }
}


Der Der :: operator+(Der g){
    Der h;
    h.f = this->f + g.f;
    for(int i=0; i< df.size(); i++){
        h.df[i] = this->df[i] + g.df[i];
    }
    return h;
}

void Der :: print(){
    cout<<"Function value at given point is : "<<f<<endl;
    for(int i=0; i< df.size(); i++){
    cout<<"Derivative at given point is : "<<df[i]<<endl;
    }
}

int main()
{
    Der f;
    vector <double> t {3,1,0};
    vector <double> k {2,0,1};
    Der x(&t),y(&k);
    
    f = x+y;
    f.print();
}

Thank you very much!


Solution

  • In your constructor your vector df is empty but you attempt to put values into the vector using

    this -> df[i-1] = v->at(i);
    

    This will result in undefined behavior because you are accessing outside the bounds of the empty vector. One way to fix is to replace that line with this:

    df.push_back(v->at(i));
    

    which will increase the size of the vector at each call.

    Also in Der Der :: operator+(Der g){ you have:

    h.df[i] = this->df[i] + g.df[i];
    

    has the same bug as the constructor. h.df is empty. You can fix that with:

    h.df.push_back(this->df[i] + g.df[i]);
    

    Also like @πάντα ῥεῖ mentioned in c++ we prefer passing by const reference over a pointer:

     Der :: Der(const vector <double>& v){