-2

i am unsure as to why my copy constructor seems to be crashing the program, all the other functions have been fine in the linked list class. The rule of 5 is really confusing me now with implementation. If anyone has some pointers or guidance of where I am going wrong please let me know, thanks.

DList ctor:

DList() {
    //Node* front_;
    front_ = new Node(); // creating front sentinel
    //Node* back_;
    back_ = new Node(); // creating back sentinel
    //make them point to eachother
    front_->next_ = back_;
    back_->prev_ = front_;
    listSz = 0;
}

destructor and copy constructor:

//destructor
~DList() {

    Node* current = front_;

    while (current != back_)
    {
            front_ = front_->next_;
            delete current;
            current = front_;
    }
}
// copy ctor
DList(const DList& rhs) {
    cout << "in ctor" << endl;
    const Node* current = rhs.front_;
    Node* temp = nullptr;
    if (current != rhs.back_)
    {
        cout << "in if" << endl;
        front_ = new Node(current->data_);
        temp = front_;
        current = current->next_;
    }
    while (current != rhs.back_)
    {
        cout << "in while" << endl;
        Node* nn = new Node(current->data_);
        temp->next_ = nn;
        temp = temp->next_;
        current = current->next_;
    }
    cout << "test";
}

main:

int main(void) {
    DList<int> list;
    DList<int> list2;
    DList<int>::const_iterator it;

    cout << list.size() << endl;
    list.push_front(1);
    list.push_front(2);
    list2.push_back(3);
    list2.push_front(4);
    list.print();

    std::cout << endl;


    list2.print();

    DList<int> list3 = list;
    list3.print();
}

output before crashing:

0
2
1

4
3
in ctor
in if
in while
in while
test
2
1
J. Piquard
  • 1,665
  • 2
  • 12
  • 17
bb13
  • 9
  • 6

1 Answers1

2

Taking a closer look at these three lines:

const Node* current = rhs.front_;
...
if (current != back_)
...
while (current != back_)

The pointer current is using the list from the other DNode class. But back_ is the member of the currently uninitialized class (it is this->back_), and will therefore have an indeterminate value. This will lead to undefined behavior

I'm sure you mean rhs.back_ instead.

There are also many other problems in how you copy the other list, like for example you never actually initializing back_ in the copy-constructor.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • @bb13 That would coincide with the whole, "There are also many other problems in how you copy the other list...". It's time to break into your debugger and start single-stepping. – WhozCraig Feb 25 '17 at 10:08