[英]getopt(): Is optarg guaranteed to be non-NULL if optstring contains something like “a:”?
When I am writing a piece of code, say something like this: 当我编写一段代码时,说出这样的话:
int i_flag;
char *s;
while ((c = getopt (argc, argv, "i::o:")) != -1) // I know "i::" is a GNU extension
switch (c) {
case 'i':
i_flag = 1;
if (optarg != NULL)
str-i = optarg;
break;
case 'o':
id = strtol (optarg, &s, 0);
if (id < 0 || id > 5 || *s) {
fprintf(stderr, "Invalid ID: %s\n", optarg);
print_usage(); // this function exit()'s the program
}
break;
default:
print_usage();
}
My question is that I know optarg
can be NULL in the 'i'
case, but can it be NULL in the 'o'
case? 我的问题是我知道optarg
在'i'
情况下可以为NULL,但是在'o'
情况下可以为NULL吗? I think it should not be NULL at all, but it does not seem to be guaranteed in POSIX. 我认为它根本不应该为NULL,但是在POSIX中似乎无法保证。
I have this question since a very smart static analyzer looks at if (optarg != NULL)
and says "Oh, so optarg
can be NULL and you didn't check it in case 'o'
. 我有这个问题,因为一个非常聪明的静态分析器会查看if (optarg != NULL)
并说“哦,所以optarg
可以为NULL,并且您没有检查它是否为case 'o'
。
Update : Fix int i-flag;
更新 :修复int i-flag;
. 。
Yes, optarg
will be non-null. 是的, optarg
将为非null。 If a argument is omitted for an option that requires one, getopt
will return '?'
如果对于需要选项的选项省略了参数,则getopt
将返回'?'
. 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.