Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

basic_string::_S_construct null not valid

Tags:

c++

I am reading an input file from the command line.

int main(int argc, char **argv)
{
    Scene myScene;
string filename = argv[1];
myScene = Parser(filename);
 ...
}

from another file I use the parser function which is declerated like that;

Scene Parser(string filename)
{
 string line;
 ifstream myfile (filename.c_str());
 ...
 return scene;
}

I am getting the error; terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_S_construct null not valid

Program received signal SIGABRT, Aborted.

I have searched the error. I think it is because of these lines. But I cannot find the actual reason. Can anybody help me?

like image 211
starrystar Avatar asked Jan 11 '14 22:01

starrystar


2 Answers

This means that filename is NULL in Parser, probably because you are not passing any arguments to your program's command line.

Make sure to always check whether the expected number of arguments are passed to your program. For instance, you could do :

int main(int argc, char *argv[]) {
   if (argc != NUMBER_OF_EXPECTED_ARGUMENTS) {
      exit(EXIT_FAILURE);
   }
   // ...
   string filename(argv[1]);
   Scene myScene = Parser(filename);
   // ...
}
like image 81
Halim Qarroum Avatar answered Nov 15 '22 17:11

Halim Qarroum


It is possible that you forgot to specify command line arguments and as the result argv[1] is equal to NULL. You should check whether the user entered command line arguments. For example

int main(int argc, char **argv)
{
    Scene myScene;
    string filename;
    if ( 1 < argc ) filename.assign( argv[1] );
like image 20
Vlad from Moscow Avatar answered Nov 15 '22 16:11

Vlad from Moscow