【问题标题】:*** glibc detected *** free(): invalid pointer:*** 检测到 glibc *** free():无效指针:
【发布时间】:2012-10-18 17:35:31
【问题描述】:

对于上述 glibc 错误的原因,我完全感到困惑。我一定遗漏了一些明显的东西,但每次以下程序(由 4 个文件组成)退出时都会出现:

TankSim.h:

#ifndef TANKSIM_WDECAY_TANKSIM_H_
#define TANKSIM_WDECAY_TANKSIM_H_

#include <cstdlib>
#include <iostream>

#include "Parser.h"

int main();

#endif

TankSim.cpp:

#include "TankSim.h"

using std::cout;
using std::endl;

int main()
{
     const Settings gGlobals = ParseConfig();

     return(0);
}

解析器.h:

#ifndef TANKSIM_WDECAY_PARSER_H_
#define TANKSIM_WDECAY_PARSER_H_

#include <cstdlib>
#include <vector>
#include <fstream>
#include <sstream>
#include <iostream>

struct Settings {
  double speedlight;
  double refractiveindex;
  double absorptionchance;
  double pmtradius;
  double photspermetre;
  double tankradius;
  double tankheight;
  long unsigned int randomseed;
  double scatterangle;
  std::vector<double> entrypoint;
  std::vector<double> entrydrn;
};

Settings ParseConfig();

#endif

解析器.cpp:

#include "Parser.h"

using std::string;
using std::vector;
using std::cout;
using std::endl;

Settings ParseConfig()
{
  Settings settings;

  std::ifstream configfile("settings.dat");

  string line;
  while(getline(configfile,line)){
    //Comments start with %
    if(line.find("%") != string::npos){
      cout << "Comment: " << line << endl;
      continue;
    }

    //Read in variable name.
    std::stringstream ss;
    ss << line;
    string varname;
    ss >> varname;
    string value = line.substr(varname.length()+1);
    cout << varname << "-" << value << endl;
  }
}

由于我没有明确调用任何删除运算符,我不知道为什么会发生错误。

【问题讨论】:

  • return 语句在哪里?
  • @BobFincheimer - 这就是我的想法 - 应该返回一个“设置”。
  • 天哪。非常感谢 - 我今天过得不好!
  • @Wheels2050 如果这确实是问题,请接受。

标签: c++ glibc


【解决方案1】:

很可能是缺少返回语句。

然后在您的 main 方法中,Settings 本地对象永远不会被初始化。然后它的作用域结束,其中向量的析构函数被调用,它们认为它们有一个指针(因为它们是用内存中的垃圾初始化的)并在它们的指针上调用 delete。

添加-Wall 以启用所有警告将在未来告诉您这一点。

【讨论】:

    猜你喜欢
    • 2013-08-01
    • 2012-05-04
    • 1970-01-01
    • 2016-06-16
    • 1970-01-01
    • 2016-03-27
    • 2016-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多