【问题标题】:seg fault after end of function (C++)函数结束后的段错误(C++)
【发布时间】:2014-02-12 11:51:47
【问题描述】:

运行特定程序时出现段错误:11。在我将系统升级到 Mac OS X 10.9 之前,我觉得这个问题不存在,但我可能只是忽略了它..

反正我的函数是这样的:

// this applies a warp to  the field given, and saves output.  simple!
void Apply(string warpName, string fieldName, bool conserve, string outName) {

  // get lon, lat dimensions of warp
  int noLongs = GetDimension(warpName, 3, "warp");
  int noLats = GetDimension(warpName, 2, "warp");

  int origNoLongs = noLongs, origNoLats = noLats;

  // read in params
  vector<double> params = ImportWarpFromNetCDF(warpName);

  // rescale field to warp's dimensions, and read in
  string tempName = "scaledField";
  ReScale(fieldName, tempName, noLongs, noLats);
  vector<vector<vector<double> > >inIntensities = ImportFieldFromNetCDF(tempName);
  RemoveFile(tempName);

  // just enter inIntensities for ref image, and 1 for lambda, to keep objective function happy
  ObjectiveFunction objective(inIntensities, inIntensities, conserve, 1, false);
  objective.setParameters(params);

  // output files
  ExportOutputToNetCDF(objective, outName);

  cout << "BAH?!" << endl;

}

最后的 cout 行只是检查我是否正确地到达了函数的末尾(我有)。关于为什么这会在这里出现段错误的任何想法?我很感激如果不查看各个函数调用的作用可能很难判断,因此我会在必要时添加它们。

其实没什么大不了的,因为这个函数是最后被调用的(所以段错误不会中断任何东西),但我还是更愿意深入了解它!

【问题讨论】:

  • 如果段错误发生在cout 之后但在函数返回之前,那么它将位于局部变量之一的析构函数中。您的调试器应该准确地告诉您它发生的位置。

标签: c++ segmentation-fault void


【解决方案1】:

函数“之后”发生的唯一事情是析构函数调用。检查所有局部变量的析构函数。看起来ObjectiveFunction 是唯一一个不是原始或标准库容器的局部变量,因此请检查ObjectiveFunction::~ObjectiveFunction() 是否存在潜在问题。

【讨论】:

  • 很好地发现 - 在 ~ObjectiveFunction 中有一个调用来删除一个没有为这种类型的 ObjectiveFunction 设置的指针!我现在已经将此删除包含在 if 子句中,这样我们就不会尝试删除不存在的内容。非常非常感谢!
猜你喜欢
  • 1970-01-01
  • 2012-10-16
  • 2019-03-15
  • 2012-03-11
  • 2019-08-03
  • 1970-01-01
  • 1970-01-01
  • 2015-07-14
  • 1970-01-01
相关资源
最近更新 更多