[英]Why does popt segfault when a string is too short?
Why would popt be segfaulting when the argDescrip
string isn't long enough? 当
argDescrip
字符串不够长时,为什么popt会出现段argDescrip
?
Take the following example: 请看以下示例:
#include <popt.h>
struct poptOption options[] = {
POPT_AUTOHELP
{
.longName = "color",
.shortName = '\0',
.argInfo = POPT_ARG_STRING
| POPT_ARGFLAG_OPTIONAL
| POPT_ARGFLAG_SHOW_DEFAULT,
.arg = (void*) "auto",
.val = 1,
.descrip = "Whether or not to use colored output",
.argDescrip = "always|never|auto (checks if TTY)"
},
POPT_TABLEEND
};
int main(int argc, const char** argv) {
// get popt context
poptContext ctx = poptGetContext(
"program",
argc, argv,
options,
POPT_CONTEXT_POSIXMEHARDER);
// parse
poptGetNextOpt(ctx);
return 0;
}
The above segfaults: 上面的段错误:
/tmp$ ./a.out --help
Usage: a.out [OPTION...]
[1] 47468 segmentation fault ./a.out --help
Although changing .argDescrip
to 虽然将
.argDescrip
更改为
.argDescrip = "always|never|auto (checks if TTY) "
"........................................."
popt happily accepts it and displays the output: popt愉快地接受它并显示输出:
/tmp$ ./a.out --help
Usage: a.out [OPTION...]
--color[=always|never|auto (checks if TTY) .........................................] Whether or not to use colored output
Help options:
-?, --help
Show this help message
--usage
Display brief usage message
What gives? 是什么赋予了? Am I missing something in the C spec?
我在C规范中缺少什么吗? The popt man pages don't specify a required length.
popt手册页未指定所需的长度。 Is this a bug?
这是错误吗?
Your problem is something else. 您的问题是其他问题。 You have set the
arg
member to a constant string while you would have needed to set it to a pointer to such (the man page says, arg should be initialized with a pointer to char *
). 您已经将
arg
成员设置为常量字符串,而您需要将其设置为指向此类的指针(手册页中说,arg应该使用指向char *
的指针进行初始化)。 Your program dies while trying to dereference a pointer that isn't one. 您的程序在尝试取消引用不是一个的指针时死亡。
Try like this: 尝试这样:
char *garg = "auto";
struct poptOption options[] = {
POPT_AUTOHELP
{
.longName = "color",
.shortName = '\0',
.argInfo = POPT_ARG_STRING
| POPT_ARGFLAG_OPTIONAL
| POPT_ARGFLAG_SHOW_DEFAULT,
.arg = &garg,
.val = 1,
.descrip = "Whether or not to use colored output",
.argDescrip = "always|never|auto (checks if TTY)"
},
POPT_TABLEEND
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.