c++ - 段错误 ||访问违规写入位置

标签 c++ linked-list segmentation-fault fault

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

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;

关于c++ - 段错误 ||访问违规写入位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13355354/

相关文章:

c++ - Gradle-Visual C++编译器,vcpkg和外部库

c++ - OpenCV 3.1.0 : Accessing single elements from a UMat

c - 我的 if 语句与我想要的相反

java - 数组类型相同,链表类型不同

c - 如何调用链接列表中的特定条目? C

python - 使用 f2py 的段错误

iOS 试图解决严重的崩溃问题

c++ - 从基调用非虚拟成员函数

c++ - 在C++中生成1到3之间的随机数

c - 在C中使用插入排序对字符串进行排序 - 段错误