簡體   English   中英

在OS X Mavericks上使用-O3進行編譯時,出現Getopt代碼段錯誤

[英]Getopt code segfaults when compiling with -O3 on OS X Mavericks

我最近注意到,當給定以雙破折號開頭的參數時,例如--help我已經編寫了一些程序(使用libgetopt)segfault。

我設法用下面的小程序重現了這一點:

#include <getopt.h>

int main(int argc, char *argv[]) {
    // Parse arguments.
    struct option long_options[] = {
        { "test", required_argument, 0, 't' }
    };
    int option_index, arg;
    while((arg = getopt_long(argc, argv, "t:", long_options, &option_index)) != -1);

    return 0;
}

當我使用./a.out --help編譯並運行此程序時,它可以正常工作。 但是,一旦我使用-O3編譯,它就會出現段錯誤。 在OS X Mavericks(10.9)上使用Apple LLVM版本5.0(clang-500.2.79),可以觀察到此行為。

有什么我可以解決的方法,還是我將來應該避免使用-O3

從手冊頁獲取getopt_long

 The last element of the longopts array has to be filled with zeroes.

所以你需要的是另一條線

struct option long_options[] = {
    { "test", required_argument, 0, 't' },
    { 0 } // this line is new
};

我懷疑是這種情況,因為我查看了您的代碼並詢問:“ getopt_long如何知道數組中有多少個元素”。 手冊頁已確認。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM