0

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?

4
  • DO NOT USE or, in C++11 this is defined as ||, there are a few of these (I forget the name)s in C++ <--- notice the absence of 11, in C++ in general; like :[ is a way of typing { or something, I've never used them, but they're there! Commented Mar 18, 2014 at 23:30
  • Why does copy constructor has to deal with the global variable head ? Copy constructor has to change the change the state of this. Commented Mar 18, 2014 at 23:39
  • The head variable is part of the class that the copy constructor is apart of Commented Mar 18, 2014 at 23:47
  • You allocate a bunch of ListNode objects, but you don't actually store pointers to them anywhere. At the end, you have this->head == org->head and a bunch of leaked objects. Commented Mar 18, 2014 at 23:47

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.