samedi 2 mai 2020

Segmentation fault in copy constructor for a list [closed]

I am trying to create a list container (not using std::list) and I'm having trouble with copy constructor. As far as I understand when dealing with dynamic memory copy constructor must be created to avoid two objects pointing the same memory.

I created a BaseListElement class from which other classes are derived and a MyList class that actually manages the list.

And I am implementing BaseListElement derived class

class ListElement: public BaseListElement {

public:
    ListElement();
    ~ListElement();

    void copy(ListElement *to_copy) ;
...
}

Copy is a method that intends to be called by MyList with ptr_to_head. _ptr_to_next_element is member of the base class but it should be inherited from derived class

void ListElement::copyField(ListElement *to_copy) {
//Delete all content
if(this_ptr_to_next_element!= nullptr) //Segmentation fault here
{
    delete _ptr_to_next_element;
}
if(to_copy!=nullptr)
{
    if(to_copy->getNextElement()!= nullptr)
    {
        //Alloc memory for next element and recall this function with that element
    } else{
        _ptr_to_next_element= nullptr;
    }
    //Copy Data
} else{
    ...
}
} 

When the code is executed I get segmentation fault when accessing this->_ptr_to_next_element and don't understand why. At the beginning that ptr is nullptr.

Thank you very much

Aucun commentaire:

Enregistrer un commentaire