Question

This code works for several thousand calls in a row if the r's are addressed sequentially. It works for a few hundred in a row if the r's are selected randomly.

However, at some point in the random r's, I get a segmentation violation. I am not sure what could be causing this since it works fine almost all of the time.

*** Break *** segmentation violation
Segmentation fault

The crash occurs at fgets.

int fsize(int r, double VME, std::string* filepath) {
  FILE *statfile;
  std::stringstream streamfilename;
  std::stringstream streamcommand;
  string* filename = new string;
  std::string command;
  char buffer [15];
  char charsize;
  streamfilename.str("");
  streamfilename << *filepath << "run" << r << "-" << VME << ".dat";
  *filename = streamfilename.str();
  streamcommand.str("");
  streamcommand << "stat -c " << "%s " << *filename;
  command = streamcommand.str();
  const char * charcommand = command.c_str();
  statfile = popen(charcommand, "r");
  cout << "Test 5\n";
  while(fgets(buffer,15,statfile)!=NULL){}; CRASH OCCURS HERE
  cout << "Test 6\n";
  int* filesize = new int;
  *filesize = atoi(buffer);
  pclose(statfile);
  return *filesize;
}

What is the cause of the segmentation fault?

Was it helpful?

Solution

statFile is probably NULL.

If you would like to get filesize, you should consider the C function :

 int stat(const char *path, struct stat *buf);

It will avoid to fork the command, and parsing its result.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top