Theo K
Theo K

Reputation: 51

C++ unable to delete a node in a linked list

I am trying to delete a node in a linked list using mylist.erase(); but the node remains in the list. I tried to use delete() but the program crashes. Any idea?

list <Person*> :: iterator it;
it = gamelist.begin(); //gamelist is a <Person*> list. it is an iterator to this list.
while (it!=gamelist.end()){
    if ((*it)->is_dead == true) {
        delete (*it); //if I comment this line the program does not crash but the "dead" Person still remains in the list.
        it = gamelist.erase(it);
    }
    else ++it;
}

Upvotes: 3

Views: 126

Answers (1)

eerorika
eerorika

Reputation: 238321

Deleting a pointer has no effect on whether the pointer remains in a container. Since you haven't shown a program that demonstrates that shows that the node remains in the list, I posit that it does not remain after the call to erase.

If you allocated the pointed object with new, then you must delete it at some point. If the program crashes when you delete the pointer here, that means that either

  • The pointer is uninitialized and has never pointed to a valid object.
  • The pointer used to be valid, but the pointed object has already been destroyed, and the pointer is no longer valid.
  • The pointer is valid, but points to an object that was not created with new.
  • The pointed object is not in a valid state that its destructor depends on.

It is not possible to "test" the validity of the pointer within the program (except for checking whether it is null, but deleting null is OK and would not crash, so that's not the problem in your case). You must analyze your program and guarantee the validity yourself. Smart pointers make reasoning about the validity of pointers far easier. I recommend you to use them.

Upvotes: 4

Related Questions