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
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.