开发者

Segfault when inserting a new element into a sorted linked list

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开发者_JS百科; 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, TempPrevious will an uninitialized pointer. When you try running the for loop on an empty list, TempNext will immediately be NULL and you won't execute the statement TempPrevious = TempNext. Since you never set TempPrevious to have a default value, it will be uninitialized, and so the code

TempPrevious -> Next = NewNode;

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


It's been a while since I've done C++, but is it because TempPrevious is created but never assigned?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜