Segmentation fault (core dumped) when I delete pointer

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

    There are many answers stating that new/delete and malloc()/free() should always be paired so, but I feel that it should be said why exactly.

    As in your initializations,

    Node *h = new Node('H');
    

    the new keyword returns a fully typed object object pointer, defined in the statement itself, while malloc() simply allocates a given memory space without assigning a type, and so returns a void*. Additionally, new/delete deal with memory from the Free Store while malloc()/free() allocate/free memory on the Heap, although some compilers might implement new/free in terms of malloc()/free in some instances.

    Also of some importance is that new and delete call the constructor and destructor respectively, while malloc() and free() simply allocate and deallocate heap memory, with no regard for the state of the memory itself.

提交回复
热议问题