gpt4 book ai didi

c++ - 链表,C++段错误

转载 作者:行者123 更新时间:2023-11-30 01:25:13 24 4
gpt4 key购买 nike

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

我正在尝试将节点添加到文件的链表中。我已经运行了多个测试并且已经缩小了问题的范围,但是,我不知道到底是什么导致了这个问题,因此当我尝试更改其他细节时我会产生新的问题。

这是我的第二门类(class),因此,希望我的代码没有糟糕到无可救药的地步。这是添加方法:

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

在此先感谢,如果有必要确定此问题,我将很乐意发布更多代码。

最佳答案

if(previous = NULL)

代替

if(previous == NULL)

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

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

导致未定义的行为。

关于c++ - 链表,C++段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12687139/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com