Linked lists and new/delete?

This is a discussion on Linked lists and new/delete? within the C++ Programming forums, part of the General Programming Boards category; Alot of the tutorials on linked lists that i have gone through lately, uses the new operator to allocate memory ...

Linked lists and new/delete?

Alot of the tutorials on linked lists that i have gone through lately, uses the new operator to allocate memory for a new node in the list, but never checks if the allocation failed, and they don't use the delete operator to clear the memory afterwards either, this includes the tut on cprogramming.com. Why is that? Is there a particular reason?

Also, i've tried to make a loop to destroy a linked list of mine after usage, but i keep getting segmentation errors when i run it:

Prelude's tutorial in the FAQ here has a paragraph on deleting the memory (basically the same thing you do).

Alot of the tutorials on linked lists that i have gone through lately, uses the new operator to allocate memory for a new node in the list, but never checks if the allocation failed, and they don't use the delete operator to clear the memory afterwards either, this includes the tut on cprogramming.com. Why is that? Is there a particular reason?

It is quite annoying and complicated to check everything (new throws an exception, and you might need smart_pointers instead of regular ones to be safe), therefore most tutorials leave error-checking out to keep the focus on the issue at hand.

One problem with this code is you're calling delete on a pointer that you haven't checked to be NULL. You get a seg fault when you're at the last node in the list and calling delete on the next pointer which is NULL. Also, as pointed out, you're actually traversing 2 nodes each iteration which will cause memory leaks.

Code:

IF head != NULL
WHILE head->next != NULL
temp = head
head = head->next
delete temp
END WHILE
delete head
head = NULL
END IF