Home > Software design >  Segmentation fault when initialize an array after create object of template class
Segmentation fault when initialize an array after create object of template class

Time:10-19

Below is my linked list template class and i define it in "LinkedListTemplate.h":

template<typename T> class Node{
T data;
Node<T> *next;
public :
    void setData(T new_data){
        data = new_data;
    }
    Node<T>* &getNext(){
        return next;
    }
    T getData(){
        return data;
    }
};

template<typename T> class LinkedList{
private :
    Node<T> **head_ref;
public :
    LinkedList(){
        (*head_ref) = NULL;
    }
    void insert(T data){
        Node<T> *new_node = new Node<T>;
        new_node->setData(data);
        new_node->getNext() = (*head_ref);
        (*head_ref) = new_node;
    }
    void printList(){
        Node<T> *current = (*head_ref);
        while(current != NULL){
            cout << current -> getData() << " ";
            current = current -> getNext();
        }
    }
    Node<T> *getHead() const{
        return (*head_ref);
    }
    void deleteList(){
        Node<T> *current = (*head_ref);
        Node<T> *next;
        while(current != NULL){
            next = current -> getNext();
            delete current;
            current = next;
        }
        (*head_ref) = NULL;
    }


};

So i want to use this template class to create a class name Set used to manage a set of integer it have a constructor that use given array and size and i define this class in "4-5.h" header

class Set{
private :
    LinkedList<int> l;
public :
    Set() {}
    Set(int a[], int size){
        for(int i = 0; i < size; i  )
            l.insert(a[i]);
    }
    ~Set(){
        l.deleteList();
    }
};

So in my main when i create an object using default construct to create object it work normally but when i initialize an array of int i got segmentation fault like below :

int main()
{
    Set s1;
    cout << s1; // This work fine 

    int a[] = {2,3} // When i initialize it i got segmentation fault

    return 0;
}

CodePudding user response:

template<typename T> class LinkedList{
private :
    Node<T> **head_ref;
public :
    LinkedList(){
        (*head_ref) = NULL; // HERE
    }

What do you think head_ref points to in the line that I marked?

You never initialize head_ref. So when you do (*head_ref) you are dereferencing a pointer that doesn't point to anything.

  •  Tags:  
  • c
  • Related