C语言 Getopt 错误:内存保护冲突



我尝试使用getopt,但我有一个问题。 运行./a.out -A -R后,我看到memory protection violation. 我做错了什么?

int c;
int rec_flag=0;
int copy_range=0;
while((c=getopt(argc,argv,"AR:"))!=-1){
switch(c){
case 'A':
copy_range=1;
break;
case 'R':
rec_flag=1;
break;
case '?':
if (optopt == 'c')
fprintf (stderr, "Option -%c requires an argument.n", optopt);
else if (isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.n", optopt);
else
fprintf (stderr,"Unknown option character `\x%x'.n",optopt);
return 1;
default:
abort ();
}
}
while((c=getopt(argc,argv,"AR:"))!=-1){
switch(c){
...
case '?':  if (optopt == 'c')
fprintf (stderr, "Option -%c requires an argument.n", optopt);

getopt不会在您的程序中将optopt设置为"c"。

在您粘贴此内容的示例代码中,格式字符串为"abc:"。 因此,如果在没有参数的情况下传递-coptopt将是"c"(如上所述,格式字符串中的冒号表示它需要)。 您的程序根本没有-c选项。 您没有删除第三个选项规范,因为您的程序接受 2 个参数...右?

确保你像它所说的那样 #included<unistd.h><ctype.h>,然后尝试将getopt变量声明为externMemory protection violation可能意味着链接器当前正在将它们作为可传递包含拉入,但内核不希望您的进程访问 libc 的一部分映射到的共享内存区域。 只是一个猜测,但它确实清除了我在尝试运行代码时遇到的一些不当行为。

https://www.gnu.org/software/libc/manual/html_node/Using-Getopt.html#Using-Getopt https://www.gnu.org/software/libc/manual/html_node/Example-of-Getopt.html#Example-of-Getopt

最新更新