***glibc检测到***free():指针无效:

Whe*_*050 2 c++ glibc

我完全被上述glibc错误的原因所困扰.我必须遗漏一些明显的东西,但每次出现以下程序(由4个文件组成)时都会出现:

TankSim.h:

#ifndef TANKSIM_WDECAY_TANKSIM_H_
#define TANKSIM_WDECAY_TANKSIM_H_

#include <cstdlib>
#include <iostream>

#include "Parser.h"

int main();

#endif
Run Code Online (Sandbox Code Playgroud)

TankSim.cpp:

#include "TankSim.h"

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

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

     return(0);
}
Run Code Online (Sandbox Code Playgroud)

Parser.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
Run Code Online (Sandbox Code Playgroud)

Parser.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;
  }
}
Run Code Online (Sandbox Code Playgroud)

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

Bob*_*mer 6

很可能是它缺少的退货声明.

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

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