简体   繁体   中英

Why am I getting “segmentation fault” when i try to run copy constructor?

The copy function executes when I quit the function and then prints the current contents of the circular linked list. What i'm trying to do is to have an object named other point to the original list before it is deleted (which is the original list before the program quits). Then i assign the data from the original list into the nodes of the new list. Since the first or head node is the largest I used while ( p->info.= p->next->info ) as the condition to copy all of the contents before the node and then if (p->info == other.first->info) to identify the head node and then make that nodes data or info equal to the head of the node of the copied list.

'''

//Copy constructor function

  template <class T>
    void CLList<T> :: copy ( const CLList<T> & other )
    {
       if ( other.first == NULL )
     first = NULL;
   else
   {
  first = new node<T>;
  first->info = other.first->info;

  node<T> *p = other.first->next;
  node<T> *r = first;

  
  while ( p->info != p->next->info )
  {
      r->next = new node<T>;
      r->next->info = p->info;
   if (p->info == other.first->info)
  {
    r->next = new node<T>;
    r->next->info = other.first->info;
  }


// Node 
 template <class T>
  struct node
{
    T info;
     node *next; 
  };

This code is all wrong for a copy constructor. The while loop is not actually iterating the input list at all, it is just copying the 1st node over and over. Also, the loop should not be comparing info values at all.

This code needs to be completely rewritten. Try something more like this instead:

template <class T>
CLList<T>::CCList(const CLList<T> &other)
    : first(NULL)
{
    node<T> *p = other.first;
    node<T> **r = &first;

    while (p)
    {
        *r = new node<T>;
        (*r)->info = p->info;
        (*r)->next = NULL;
        r = &((*r)->next);
        p = p->next;

        // for a circular list only:
        if (p == other.first) break;
    }

    // for a circular list only:
    if (r != &first) *r = first;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM