繁体   English   中英

Getopt错误:内存保护违规

[英]Getopt error: memory protection violation

我尝试使用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个参数......对吗?

确保#include <unistd.h><ctype.h>一样,然后尝试将getopt变量声明为extern Memory 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的#实施例-的-的Getopt

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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