分段故障执行方法
我编码的相关(我认为)行如下。
是什么意思是有一个群集列表。
其中一个, base
,将吸收另一个( aborbed
)。 aborbed
群集应从列表中删除
。
The relevant (I think) lines of my coding are below.
What is meant is that there is a list of Clusters.
One of them, base
, will absorb another one (the aborbed
).
The aborbed
cluster should be erased from the list
.
我遇到的第一个问题是我需要在 base
和吸收的
集群中执行其他操作,在之后
循环关闭。
从我的搜索中,我找到了 =&(* li)
的东西。我理解的是,我得到一个指向元素 li
指向的地址的指针,虽然我做不到 absorb = li
,因为一个是迭代器而另一个是(简单?)ponter。我很感激对此有一些解释。
First problem I encountered was that I needed to perform other operations in both base
and absorbed
clusters, after while
cycle closes.
From my searches, I found the = &(*li)
stuff. What I understand is that I get a pointer to the address of the element li
points to, although I cannot do absorbed = li
, because one is an iterator and the other a (simple?) ponter. I'd appreciate some explanation on this.
现在,更大的问题是我在行 c-> getPoints中遇到了一个分段错误();
方法 joinCluster()
我做错了什么?我应该怎么做?
Now, the bigger problem is that I get a sementation fault in the line c->getPoints();
of the method joinCluster()
What am I doing wrong? What should I do an why?
我在Linux x86_64中使用g ++(GCC)4.5.2。
I'm using g++ (GCC) 4.5.2 in Linux x86_64.
Cluster * base;
Cluster * absorbed;
list<Cluster>::iterator li = clusters.begin();
while ( li != clusters.end() ) {
if (li->getId() == p2) {
absorbed = &(*li);
li = clusters.erase(li);
} else if (li->getId() == p1) {
base = &(*li);
}
++li;
}
base->joinCluster(absorbed);
void Cluster::joinCluster(Cluster * c)
{
set<unsigned int> pts = c->getPoints();
}
set<unsigned int> Cluster::getPoints()
{
return points;
}
class Cluster {
private:
std::set<unsigned int> points;
public:
std::set<unsigned int> getPoints();
};
list<Cluster>::iterator li = clusters.begin();
while ( li != clusters.end() ) {
if (li->getId() == p2) {
absorbed = &(*li);
li = clusters.erase(li);
} else if (li->getId() == p1) {
base = &(*li);
}
++li; // <---- Don't increment when you already deleted.
}
当您删除列表中的最后一个元素时, li
变为 cluster.end()
。然后你再次增加它并且繁荣,你已经出界了。 ++ li
应该进入 else
阻止。
When you delete then last element in the list, li
becomes cluster.end()
. Then you increment it again and boom, you're out of bounds. ++li
should go in else
block.
另请注意,当您从容器中删除 li
时,吸收
会保留无效的地址。
Note also, when you erase li
from the container, absorbed
holds an invalid adress.