user2340686
user2340686

Reputation: 97

Using a copy constructor with a linked list

In my project I am trying to make it so I can make a copy of a linked list then display its contents. Currently I have it working but every time I try to exit the program crashes. I removed the instance of the copy constructor being used in the main part of the program so the problem seems to be coming from there. Here is the code:

struct ListNode{
    int num;
    struct ListNode *next;
};
ListNode *head;

List::List( const List& org){
   ListNode *copy=org.head;
   ListNode *temp;
   if(copy==NULL){
     head=NULL;
   }
   else{
     head=copy;
     while(copy!=NULL){
        temp=new ListNode;
        temp->num=copy->num;
        temp=temp->next;
        copy=copy->next;
     }
   }

}

Please note that I know that some of the brackets {} are a little off the program itself works up until I try to exit so I'm wonder how I would prevent the program from crashing?

Upvotes: 0

Views: 120

Answers (2)

SleuthEye
SleuthEye

Reputation: 14579

The newly created List has a head that points at the copied instance's head. So if you delete those two list, you'll wind up trying to delete the same memory twice (I am assuming that your destructor does attempts to delete the nodes). By the way, the created nodes are allocated, but not referenced (ie. you have a memory leak). You may want to look at Coding a function to copy a linked-list in C++ for some answers to a very similar question.

Upvotes: 0

vonbrand
vonbrand

Reputation: 11791

Take a large sheet of paper, sketch a list to be copied (let's say with 4 nodes), and follow what must be done step by step. Then see how to translate that into code.

The above code creates a bunch of disconnected nodes, not a list.

Upvotes: 2

Related Questions