c++templatesvariables

Template class variable giving segment fault when changing it


The issue I am having is in my set_data() function. I am trying to have it set the data_field variable to d , the variable that is passed into the function, but I am getting segmentation fault whenever I try.

this is the function calling the class

For the test run variable i is an int that I am trying to add to the node data_field. i the int value of i is i = 0.

template<class T>
void dlist<T>::rear_insert(T i){
    dnode<T>* temp;
    temp -> set_data(i); // function call that is causing the segmentation fault
    if(tail == nullptr ){
        tail = temp;
        head = temp;
    } else {
        dnode<T>* temp1 = tail;
        tail -> set_next(temp);
        tail = tail -> next();
        tail -> set_previous(temp1);
    }
}

Here is the full code I am using for the class giving me the error

template<class T>
class dnode{
    public:
        dnode(T d = T(), dnode *n = NULL, dnode *p = NULL) {data = d;  next = n; previous = p;}
        void set_data(T d){
            data_field = d; //The line that gives 
                            //segmentation fault
        }
        void set_next(dnode *n){next_field = n;}
        void set_previous(dnode *p){previous_field = p;}
        T data()const {return data_field;}
        dnode* next() const {return next_field;}
        dnode* previous() {return previous_field;}

    private:
        T data_field;
        dnode* next_field;
        dnode* previous_field;
};

I have used cout to check if it was recieving the correct data and it was able to print the correct data to the file. the issue is with data_field = d. I have looked over other sources and they have set up the code like I have, I am not sure why I am getting segmentation fault.

void set_data(T d){
     cout << d;
     //data_field = d; 
}

it out puts 0 which is the correct value for d. Uncommenting data_field = d causes the segmentation fault.


Solution

  • In this situation, you'd need to initialize temp to be pointing to something valid. The simplest is to do auto temp = new dnode<T>();