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.
我在这里想念的是什么?在s的情况下有些if语句?具体来说,我想介绍用户没有在命令行参数中为s分配特定值/选项的情况。
1 个解决方案
#1
5
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.)
当没有's'选项传递给程序时,案例的'分支根本不执行,没有其他任何东西将数字设置为值,这意味着后续读取会触发未定义的行为。 (当你稍后读取它时,这可能比给你一个随机值更糟糕。这是一个必须修复的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.)
(顺便说一句,你应该使用strtol而不是atoi,因为atoi会忽略语法错误。)
#1
5
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.)
当没有's'选项传递给程序时,案例的'分支根本不执行,没有其他任何东西将数字设置为值,这意味着后续读取会触发未定义的行为。 (当你稍后读取它时,这可能比给你一个随机值更糟糕。这是一个必须修复的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.)
(顺便说一句,你应该使用strtol而不是atoi,因为atoi会忽略语法错误。)