Segmentation fault (core dumped) when I delete pointer

前端 未结 5 1593
北恋
北恋 2021-01-27 04:21

I am trying to remove duplicates from a linked list, and encountered a problem, which is probably obvious and straightforward but I haven\'t used C++ in many years

5条回答
  •  攒了一身酷
    2021-01-27 04:43

    This is an addendum to other answers which correctly identify and solve the OP's immediate problem. A quick walk-though is required to explain what will happen next.

      Node *temp = cur;
      prev->next = cur->next;
      cur = cur->next;
      cur->prev = prev;
    

    At this point temp has not been cleared so next and prev still point to the two nodes that used to surround cur and are now linked together. This will cause serious problems if not for:

      free(temp); //Here is my problem!!!
    

    free fails because the value pointed to by temp was allocated by new. NathanOliver's answer has this covered, but lurking beneath is what will happen with

    delete temp;
    

    This will invoke the destructor to clean up like a good little object. Unfortunately the Node destructor looks like this:

    ~Node() { delete next; delete prev; }
    

    temp->next still points to a live node. So does temp->prev.

    Next and prev get deleted. Which calls their destructors, deleteing the two nodes they touch, and invokes a deathstorm that will destroy all of the Nodes in the list.

    If the double-deletes don't kill the program first. Each linked node will try to delete the node that just deleted them. Not good.

    Odds are pretty good that the Node destructor should just look after itself and leave the destruction of the other Nodes to the LinkedList class.

提交回复
热议问题