Segmentation fault (core dumped) when I delete pointer

前端 未结 5 1556
北恋
北恋 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:34

    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 newed 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-deleteed 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::add(Node *data), you should instead consider something like LinkedList::add(T data); then the list class itself takes care of handling the nodes.

    Otherwise, you run the risk of sending a newed node into the list, then the list deletes 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 news with frees, 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.

提交回复
热议问题