簡體   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