Pavoo Pavoo - 4 months ago 18
C Question

c optarg atoi with no args

Consider the following code:

int number;

while((w = getopt(argc, argv, "n:s:")) != -1) {

switch (w){

case 'n': {

opfile->filename = optarg;

}break;

case 's': {

number = atoi(optarg);

}break;

}
}


Now, when I leave both options or the option
s
blank, for example I start my program with no command line args, then the
number
variable still gets a random value.

What am I missing here? Some if-statement in the case of
s
? Specifically, I want to cover the case where the user doesn't assign a specific value/option to
s
in the command line arguments.

Answer

When there is no 's' option passed to the program, the case 's' branch is not executed at all, and nothing else sets number to a value, which means that subsequent reads trigger undefined behavior. (This is potentially much worse than just giving you a random value when you read from it later. It's a must-fix bug.)

But because nothing else touches number, it will be enough to change

int number;

to

int number = 0;

or whatever else you want your default to be.

(By the way, you should really be using strtol instead of atoi, because atoi ignores syntax errors.)