c++ - 在类之间返回整数时出现分段错误
问题描述
我正在使用具有多个类的程序。这个问题涉及的三个类cWorld
是cOrganism
和cPopulation
。
我正在调用一个函数,cOrganism
其中包含以下几行:
printf("Right before NewCluster\n");
int new_cluster_id = m_world->NewCluster();
printf("Right after NewCluster\n");
该函数调用(类的实例)中的NewCluster()
函数。m_world
cWorld
int cWorld::NewCluster()
{
return GetPopulation().AddCluster();
}
这反过来又AddCluster()
为世界上存在的任何人口调用该函数( 的一个实例cPopulation
)。
该AddCluster()
函数如下所示:
int cPopulation::AddCluster(){
int new_id = 0;
if(cluster_array.GetSize()!=0){
cOrgCluster clus = cluster_array[cluster_array.GetSize()-1];
int last_id = clus.GetID();
new_id = last_id+1;
}
cOrgCluster cluster;
cluster.Setup(m_world,new_id);
cluster_array.Push(cluster);
printf("Check if flow reaches here, cluster-id = %d\n",new_id);
return new_id;
}
有趣的是,我从中得到以下输出:
Right before NewCluster
Check if flow reaches here, cluster-id = 0
Segmentation fault (core dumped)
似乎 AddCluster() 正在按预期工作,但是将整数值new_id
返回给cOrganism
. 我究竟做错了什么?
注意:我之前返回的是集群对象本身而不是它的 ID,但遇到了同样的问题。认为这与返回错误指针有关,我将其更改为 ID。问题仍然存在。
解决方案
从您显示的代码来看,当您的代码崩溃时,似乎唯一发生的事情就是析构函数 forcluster
正在运行。因此,很可能是该析构函数本身存在错误,或者已经发生了一些内存损坏并且析构函数正在绊倒它。
要继续使用printf
s 进行故障排除,请在cOrgCluster
. 或者,使用调试器valgrind
来找出问题所在。
推荐阅读
- java - com.mongodb.MongoSocketOpenException 异常打开套接字
- gradle - 在构建脚本中加载其他插件之前使用 gradle 插件
- wxpython - 如何使用 wxpython 在工具栏项之间引入垂直线
- javascript - 为什么 bootstrap 不适用于 js vanilla?
- angular - 比较基于测试而不是值并设置 CSS 样式
- android - AsyncTask 被 android 杀死
- python - 了解多重共线性时多元 OLS、PLS 和岭回归之间的系数差异
- javascript - 实现 Datepicker 更改“datepicker-date-display”
- java - 如何在 gradle 构建期间包含外部 webapp 文件
- r - 在r中填充重复行值的数据框列