I am using the following function to insert a new node into a sorted linked list of integers
// Insert new element
template <class Type>
bool list<Type> :: Insert (const Type& NewElement)
{
Node *NewNode, *TempNext, *TempPrevious;
NewNode = new Node;
NewNode -> Element = NewElement;
for (TempNext = Head; TempNext != NULL; TempPrevious = TempNext, TempNext = TempNext -> Next)
{
NewNode -> Next = TempNext;
if (TempNext == Head) Head = NewNode; // Check for empty list
else if (NewNode -> Element >= TempNext -> Element) continue; // Check for correct point in list
else TempPrevious -> Next = NewNode;
return true;
}
// If execution reaches this point, then the new node goes at the end of the list
TempPrevious -> Next = NewNode;
return true;
}
Whenever I try to insert an element into an empty list using this algorithm, the program returns a segmentation fault. A check with GDB identifies the TempPrevious -> Next = NewNode; line at the very end as the cause, but execution shouldn’t be reaching there since the return true at the end of the for loop should return control to the invoking function, but for some reason it isn’t. Can anyone see where I’m going wrong here?
Notice that if the list is empty,
TempPreviouswill an uninitialized pointer. When you try running theforloop on an empty list,TempNextwill immediately beNULLand you won’t execute the statementTempPrevious = TempNext. Since you never setTempPreviousto have a default value, it will be uninitialized, and so the codeWill dereference a garbage pointer, hence your crash.
To fix this, you will either need to special-case the case when the list is empty, or use some other approach to list insertion (perhaps keeping a pointer to the node pointer to rewrite) that gracefully handles insertion into an empty list.