我一直无法完成我的作业,因为我似乎无法确定这个分段错误的来源。
我正在尝试将节点从文件添加到链表。我已经运行了多个测试并且已经将问题缩小了很多,但是,我不知道实际上是什么造成了问题,因此当我尝试更改其他细节时会产生新的问题。
这是我的第二门课程,所以,希望我的代码没有那么糟糕,以至于无济于事。这是添加方法:
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 ?? ()
这是尝试纠正不同段错误的大量工作的结果,而这个更令人惊讶。我不知道我的 setNext 方法是如何导致问题的,这里是:
void CustomerNode::setNext (CustomerNode* newNext)
{
//set next to newNext being passed
next = newNext;
return;
}
在此先感谢,如果有必要识别此问题,我将很乐意发布更多代码。