【发布时间】:2013-05-16 18:49:15
【问题描述】:
在为我的作业编写代码时,我遇到了一种奇怪的行为。代码很大,虽然没必要,我就不贴了。
问题是当我试图从向量中删除一个对象时,我遇到了分段错误。在尝试自己调试时,我发现了这一点:
如果我使用以下 sn-p 执行我的代码,我的向量为空,然后第二行出现分段错误(因为向量为空)。
cout << this->adjacencyList.empty() << endl; // yeah, I'm working with graph
cout << *(this->adjacencyList[0]) << endl; // list has pointers
但是,当我删除第二行时,它显示向量不为空,然后继续。 空向量的守卫不能保持它,分段错误来了。
你对这种行为有什么想法吗?如果这一点仍然含糊不清,我可以发布我的完整代码作为编辑。
提前致谢。
编辑:
对于那些要求“多一点”的人。
void Node :: removeEdge (string destination) // removes an edge; edge is a class that contains a pointer to another node and its weight
{
bool deleted = false;
cout << *this << endl; // output stream operator is overloaded for node class and is working properly - shows it's label and edges - no error for an edge
cout << this->adjacencyList.empty() << endl;
// cout << *(this->adjacencyList[0]) << endl; // output stream operator is overloaded for edge class - error for an edge
if (!this->adjacencyList.empty())
{
for (vector <Edge *> :: iterator itr = this->adjacencyList.begin(); itr != this->adjacencyList.end(); ++itr)
{
if (((*itr)->getAdjacent())->getLabel() == destination) // segfault here
{
Edge *temp = *itr;
this->adjacencyList.erase (itr);
delete temp;
deleted = true;
}
}
}
if (!deleted)
throw EDGE_DOES_NOT_EXIST; // one of exceptions declared in enum somewhere in my code
}
第二次编辑:
注意:我无法更改标题(它们是由助手提供的),所以不要要求我更改。
如果您对完整代码感兴趣,可以在这里找到
http://pastebin.com/iCYF6hdP - Exceptions.h - 所有异常
http://pastebin.com/1fcgHGDa - Edge.h - 边缘类声明
http://pastebin.com/C2DD6e3D - Edge.cpp - 边缘类实现
http://pastebin.com/ZNqQ1iHE - Node.h - 节点类声明
http://pastebin.com/kaVtZ3SH - Node.cpp - 节点类实现
http://pastebin.com/A7Fwsi4m - Network.h - 图类声明
http://pastebin.com/02LX0rjw - Network.cpp - 图类实现
http://pastebin.com/MRMn0Scz - main.cpp - 示例主目录
【问题讨论】:
-
adjacencyList的声明是什么? -
adjacencyList() 是一个函数,而不是一个向量。只要没有人知道这个函数实际上对你的向量做了什么,就很难说......
-
你能告诉我们“多一点”吗?
-
我已经删除了我的答案,因为我错过了关于
empty()在第一种情况下返回true的部分。当更改随机代码具有看似无关的效果时,通常会涉及未定义的行为或内存损坏。 -
存在段错误的行中有两个指针引用。其中一个必须可能无效
标签: c++ vector segmentation-fault