Pavoo Pavoo - 1 year ago 71
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;


case 's': {

number = atoi(optarg);



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

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

Answer Source

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;


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.)