简体   繁体   中英

*** glibc detected *** free(): invalid pointer:

I'm completely stumped as to the cause of the above glibc error. I must be missing something obvious, but it appears every time the following program (consisting of 4 files) exits:

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);
}

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

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;
  }
}

Since I'm not explicitly calling any delete operators, I have no idea why the error occurs.

Most likely its the missing return statement.

Then in your main method the Settings local object is never initialized. Then its scope ends and the destructor for the vectors in it are called and they think they have a pointer (because they are initialized with junk in memory) and call delete on their pointer.

Adding -Wall to enable all warnings will tell you about this in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM