首页 > 解决方案 > 在类之间返回整数时出现分段错误

问题描述

我正在使用具有多个类的程序。这个问题涉及的三个类cWorldcOrganismcPopulation

我正在调用一个函数,cOrganism其中包含以下几行:

printf("Right before NewCluster\n");
int new_cluster_id = m_world->NewCluster();
printf("Right after NewCluster\n");

该函数调用(类的实例)中的NewCluster()函数。m_worldcWorld

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。问题仍然存在。

标签: c++segmentation-fault

解决方案


从您显示的代码来看,当您的代码崩溃时,似乎唯一发生的事情就是析构函数 forcluster正在运行。因此,很可能是该析构函数本身存在错误,或者已经发生了一些内存损坏并且析构函数正在绊倒它。

要继续使用printfs 进行故障排除,请在cOrgCluster. 或者,使用调试器valgrind来找出问题所在。


推荐阅读