简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM