Chuck Onwuzuruike
Chuck Onwuzuruike

Reputation: 344

Why does c++ program crash after temporary object is destroyed at end of scope

So i'm a little bit confused. This bit of code will fail when trying to printList() after changeList() is called. But, when I REMOVE the destructor, the code runs without crashing. My question is, why? I understand that in the bit of code I have here, im passing the object by value to changeList so therefore, a temporary object is created as a copy of the parameter. Any changes made to this temp object do not affect the original object I passed in. So why does the program crash as if I was accessing a destroyed object? Shouldn't the temp object be destroyed after changeList is done and then printList should just print 1 thru 10 instead of 1 thru 45.

void printList(Node*);
void changeList(LinkedList);

int main(){

    LinkedList list;

    for (int i = 0; i < 10; i++)
        list.append(new Node(i+1, nullptr));

    changeList(list);
    printList(list.getHead());
    system("pause");
    return 0;
}

void changeList(LinkedList list){
    list.append(new Node(45, nullptr));
}

void printList(Node* head){
    Node* temp = head;
    if (temp != nullptr){
        cout << temp->value << endl;
        printList(temp->next);
    }//end if
}

Upvotes: 0

Views: 669

Answers (1)

Gabor Angyal
Gabor Angyal

Reputation: 2255

If I assume correctly the destructor of the LinkedList will destroy all the nodes in the list. I also assume that the copy constructor makes a shallow copy of the list. (If you did not implement a copy constructor explicitly, this is the default.) And this happens when you run the code:

void printList(Node*);
void changeList(LinkedList);

int main(){

    LinkedList list; //first instance is created

    for (int i = 0; i < 10; i++)
        list.append(new Node(i+1, nullptr)); // nodes added to the first instance

    changeList(list); // copy constructor called, second instance is 
                      // created with the same set of node objects


    printList(list.getHead()); // nodes does not exist any more because of
                               // the destructor called at the end of changeList


    system("pause");
    return 0;
}

void changeList(LinkedList list)  // copy constructor called, second instance is created
    list.append(new Node(45, nullptr));  // nodes added to the same chain of nodes
} // destructor is called, all the nodes are destroyed

void printList(Node* head){
    Node* temp = head;
    if (temp != nullptr){
        cout << temp->value << endl;
        printList(temp->next);
    }//end if
}

You can fix thi problem by accepting a reference parameter in the changeList function:

void changeList(LinkedList &list)  // no copy
    list.append(new Node(45, nullptr));  
} // no destructor is called

Upvotes: 1

Related Questions