分段故障执行方法 [英] Segmentation fault executing method

查看:101
本文介绍了分段故障执行方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编码的相关(我认为)行如下。
是什么意思是有一个群集列表。
其中一个, 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.

这篇关于分段故障执行方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆