c++xcodethread-exceptions

Thread exception when compiling this basic C++ code in Xcode


Everytime I compile this C++ code I get a thread exception I can't understand. What is wrong here?

#include <iostream>
#include <string>
using namespace std;

int main(int argc, char* argv[]) {
    string arg = argv[1];

    if (arg == "-r")
        cout << "First arg is -r" << endl;

    return 0;
}  

Solution

  • You forgot to check argc>=2 before assigning argv[1] to the string arg.
    Are you sure you are running this program with passing a parameter?

    A possible correction:

    #include <iostream>
    #include <string>
    using namespace std;
    
    int main(int argc, char* argv[]) 
    {
        if(argc<2)
        {
          cerr << "Not enough parameters" << endl;
          abort();
        }
    
        string arg = argv[1];
    
        if (arg == "-r")
            cout << "First arg is -r" << endl;
    
        return 0;
    }