Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/batch-file/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 分段错误| |访问冲突写入位置_C++_Linked List_Segmentation Fault_Fault - Fatal编程技术网

C++ 分段错误| |访问冲突写入位置

C++ 分段错误| |访问冲突写入位置,c++,linked-list,segmentation-fault,fault,C++,Linked List,Segmentation Fault,Fault,我想在双链接列表中插入一个节点。我通过了位置,多项式的新系数和它的幂。我没有编译错误,但在linux(g++)中有一个分段错误,当我使用Visual Studio运行它时,有一个访问冲突写入位置 Program.exe中0x00bd20ba处的未处理异常:0xC0000005:访问冲突写入位置0xcdcdcdd9 void Polynomial::insert( Term *pos, double newCoefficient, int power ) { Term *newTerm =

我想在双链接列表中插入一个节点。我通过了位置,多项式的新系数和它的幂。我没有编译错误,但在linux(g++)中有一个分段错误,当我使用Visual Studio运行它时,有一个访问冲突写入位置

Program.exe中0x00bd20ba处的未处理异常:0xC0000005:访问冲突写入位置0xcdcdcdd9

void Polynomial::insert( Term *pos, double newCoefficient, int power )
{
    Term *newTerm = new Term; // create a new node to insert

    // Link the new node to previous and next, given the position
    newTerm->prev = pos->prev;
    newTerm->next = pos;
    newTerm->prev->next = newTerm; // Here's where I'm getting the error
    newTerm->next->prev = newTerm;

    // change the coefficient and power
    newTerm->coefficient = newCoefficient;
    newTerm->power = power;
}

我做错了什么?我如何修复它?

好吧,如果
pos
是第一个节点,那么
pos->prev
必须是
NULL
。在这种情况下,语句
newTerm->prev->next=newTerm
会崩溃,因为没有
NULL->next

您应该明确检查
pos
是否是列表中的第一个节点,并相应地放置
newNode

// Link the new node to previous and next, given the position
newTerm->prev = pos->prev;
newTerm->next = pos;
if(pos->prev) newTerm->prev->next = newTerm;
newTerm->next->prev = newTerm;

pos->prev
可能为空或未初始化。您必须在使用输入之前验证输入…

请检查在执行程序的任何实例中,pos是否可以作为列表中的第一个节点。如果是,则在访问NULL指针的成员时,将导致分段错误


在编程时总是考虑极端情况,并确保你已经为它们设置了必要的条件。

我想知道为什么你自己来实现一个双链表。您可以定义一个
结构
,其中包含
系数
成员,并将其用作
标准::列表
的值类型。这将免费为您提供许多列表操作(例如插入和删除元素)。另外,
std::list
附带了适当的迭代器(而不是位置指针),用于标准算法


由于缺少
多项式
类的其余部分(它是一个类,而不仅仅是一个名称空间,是吗?),因此很难提供更具体的帮助。

分段错误通常发生在尝试取消引用空指针时


在处理指针时使用空检查被认为是一种很好的做法。在这种情况下,pos->prev似乎是空的,这导致了分段错误。

地址
0xcdcdcdd9
上写满了调试填充符。在取消引用(或为此分配)之前验证您的输入。谢谢。我完全忘记了。