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
So why I am not allowed to delete something that was newed somewhere else? Is it because it was newed outside the current scope?
You're allowed to delete
things new
ed elsewhere. This is not a problem as long as you're pointing to a valid address. The seg-fault shows up when you then try to use one of the pointers that was pointing to the now-delete
ed address.
Second, freeing the space works fine, but I feel that's like cheating!
You should only use free
when you've used malloc
and delete
when you've used new
. You should never mix them up. Also, after you delete
, get into the habit of assigning NULL
to the pointer variable.
Because I may need things to be done on my Node's destructor.
The class encapsulating the data should also do its own memory management internally. For example, the LinkedList
should manage the memory of the nodes.
This means that, if you have something similar to LinkedList
, you should instead consider something like LinkedList
; then the list class itself takes care of handling the nodes.
Otherwise, you run the risk of sending a new
ed node into the list, then the list delete
s it internally at some point, but somewhere else, the list's client still holds a reference to a now-invalid node. When the client tries to use it, bam!: seg-fault again.
What am I doing wrong? How to properly kill that removed node?
Besides mixing the new
s with free
s, the segfault is likely being triggered by an invalid memory access, so you should find the pointer that is no longer pointing to valid (i.e. undeleted
) memory.