I made a simple test program to play around with C++11 threads.
#include <iostream>
#include <stdlib.h>
#include <thread>
using namespace std;
void tee(int civ)
{
for(int loop=0; loop<19; loop++, civ++)
{
civ = civ%19;
cout << loop << "\t" << civ << endl;
this_thread::sleep_for(chrono::milliseconds(300));
}
}
void koot()
{
while(true)
{
cout << ":) ";
this_thread::sleep_for(chrono::milliseconds(300));
}
}
int main(int argc, char *argv[])
{
thread saie(tee, atoi(argv[1])),
kamaa(koot);
saie.join();
kamaa.join();
return 0;
}
It works fine as long as I supply command line arguments, but if I don’t, it crashes.
How can this be solved?
I tried checking the argument count, and if they existed, to no avail.
EDIT: I had to add this line:
if(argc < 2) return 1;
It crashes because you are accessing
which would hold a command line argument (other than the program’s name) if there was one. You should check whether
argcis greater than 1. Why greater than 1? Because the first command line argument is the name of the program itself. Soargcis always greater than0. And indexing starts at0. So ifargc == 1, onlyargv[0]is valid.