将新元素插入已排序的链接列表时的Segfault

时间:2011-03-19 20:26:45

标签: c++ data-structures linked-list

我正在使用以下函数将新节点插入到整数的已排序链接列表中

 // 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;
}

每当我尝试使用此算法将元素插入空列表时,程序将返回分段错误。对GDB的检查将最后的TempPrevious -> Next = NewNode;行标识为原因,但执行不应该到达那里,因为return true循环末尾的for应该将控制返回到调用函数,但由于某种原因它不是。谁能看到我在哪里错了?

2 个答案:

答案 0 :(得分:5)

请注意,如果列表为空,TempPrevious将是未初始化的指针。当您尝试在空列表中运行for循环时,TempNext将立即为NULL,您将不会执行语句TempPrevious = TempNext。由于您从未将TempPrevious设置为具有默认值,因此它将是未初始化的,因此代码

TempPrevious -> Next = NewNode;

将取消引用垃圾指针,从而导致崩溃。

要解决此问题,您需要在列表为空时使用特殊情况,或使用其他方法列出插入(可能保持指向要重写的节点指针的指针),以便优雅地处理插入到空列表。

答案 1 :(得分:1)

自从我完成C ++以来已经有一段时间了,但是因为TempPrevious已创建但从未分配过吗?

相关问题