链表,C++分段错误

Linked List, C++ segmentation fault

本文关键字:错误 分段 C++ 链表      更新时间:2023-10-16

我一直无法完成作业,因为我似乎无法确定这个分段错误的来源。

我正在尝试将节点从文件添加到链接列表中。我已经运行了多个测试,并将问题缩小了很多,但是,我不知道是什么真正造成了问题,因此,当我试图更改其他细节时,我会产生新的问题。

这是我的第二门课,所以,希望我的代码不会太糟糕,无法帮助我。以下是添加方法:

bool OrderedList::add (CustomerNode* newEntry)
{
if (newEntry != 0)
{
CustomerNode * current;
CustomerNode * previous = NULL;
if(!head)
head = newEntry;
current = head;
// initialize "current" & "previous" pointers for list traversal
while(current && *newEntry < *current) // location not yet found (use short-circuit evaluation)
{
// move on to next location to check
previous = current;
current = current->getNext();
}
// insert node at found location (2 cases: at head or not at head)
//if previous did not acquire a value, then the newEntry was
//superior to the first in the list. 
if(previous = NULL)
head = newEntry;
else
{
previous->setNext(newEntry); //Previous now needs to point to the newEntry
newEntry->setNext(current); //and the newEntry points to the value stored in current.
}
}
return newEntry != 0;  // success or failure
}

好的,有一个过载的运算符<包含在程序中,外部测试并不表明操作员有问题,但我也会包含它:

bool CustomerNode::operator< (const CustomerNode& op2) const
{
bool result = true;
//Variable to carry & return result
//Initialize to true, and then:
if (strcmp(op2.lastName, lastName))
result = false;
return result;
}

这是gdb的回溯:

#0  0x00401647 in CustomerNode::setNext(CustomerNode*) ()
#1  0x00401860 in OrderedList::add(CustomerNode*) ()
#2  0x004012b9 in _fu3___ZSt4cout ()
#3  0x61007535 in _cygwin_exit_return () from /usr/bin/cygwin1.dll
#4  0x00000001 in ?? ()
#5  0x800280e8 in ?? ()
#6  0x00000000 in ?? ()

这是大量工作的结果,试图纠正不同的segfault,而这一次更令人惊讶。我不知道我的setNext方法是如何导致问题的,这里是:

void CustomerNode::setNext (CustomerNode* newNext)
{
//set next to newNext being passed
next = newNext;
return;
}

提前感谢,如果有必要识别这个问题,我很乐意发布更多的代码。

这是

if(previous = NULL)

而不是

if(previous == NULL)

这将previous设置为NULL,然后进入else分支:

previous->setNext(newEntry); //Previous now needs to point to the newEntry
newEntry->setNext(current);

导致未定义的行为。

if(previous = NULL)

似乎有点可疑,因为它总是评估为false

你可以通过两种主要方式来避免这种错误:

  • 慷慨地使用const,将其撒到几乎所有你能撒到的地方,以及

  • 与某个值进行比较时,将该值放在左侧。

例如,写入

if( NULL = previous )

并得到编译错误,而不是崩溃或错误的结果。

就我个人而言,我不做左边的数值,因为我从来没有这个问题。我怀疑,部分原因是我对const相当慷慨。但作为一个初学者,我认为这是个好主意。

您可以发布所有代码,但我看到的第一个明显问题是:

if(previous = NULL)

在C/C++/Java中,当你的意思是==时,使用=是一个非常常见的错误。