链表,C++分段错误
Linked List, C++ segmentation fault
我一直无法完成作业,因为我似乎无法确定这个分段错误的来源。
我正在尝试将节点从文件添加到链接列表中。我已经运行了多个测试,并将问题缩小了很多,但是,我不知道是什么真正造成了问题,因此,当我试图更改其他细节时,我会产生新的问题。
这是我的第二门课,所以,希望我的代码不会太糟糕,无法帮助我。以下是添加方法:
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中,当你的意思是==时,使用=是一个非常常见的错误。
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 为什么我使用 std::copy() 收到运行时错误(分段错误)?
- 为什么我的代码包含错误分段错误(核心转储)?
- 为什么会出现此错误?- 分段错误(核心转储)
- 意外的运行时错误(分段错误)
- C++将文本文件读入数组,运行错误:分段错误
- mmap 错误:分段错误/指针无效错误
- 在我的代码中找不到错误....分段错误
- 错误:分段故障(核心转储)阵列
- 用string.h将错误分段到队列中
- c++字符串流转换错误:分段错误
- 为什么我的代码显示错误分段错误(核心转储)