Bob Bob - 1 month ago 22
C++ Question

Linked list deep copy constructor

I am implementing a linked list class' copy constructor which will make a deep copy. This is the code that i have:

List( const List & rhs ) {
Node* rhsFront = rhs.header->next;
Node* prev = header;
while (rhsFront) {
prev->next = new Node(rhsFront->data, nullptr);
rhsFront = rhsFront->next;
prev = prev->next;
}
}


However, it crashes at this line:

prev->next = new Node(rhsFront->data, nullptr);


What did I do wrong?

Answer
Node* prev = header;

I would guess the header there not to be initialised, thus causing the prev->next to be a random pointer (most likely something like 0) and trying to write to that point crashes the program. If so, this might work.

List( const List & rhs ) {
    Node* rhsFront = rhs.header->next;
    header = new Node(rhs.header->data, nullptr);
    Node* prev = header;
    while (rhsFront) {
        prev->next = new Node(rhsFront->data, nullptr);
        rhsFront = rhsFront->next;
        prev = prev->next;
    }
}
Comments