使用带有无法识别的长选项的`getopt_long`时出现分段错误

问题描述 投票:1回答:1

我在我的新程序中使用getopt_long函数。传递有效的长选项时运行良好。但是如果我尝试使用无效选项(即--unknown)调用程序,则会暂停执行,说明发生了分段错误。完整的命令是program version --unknown

我需要在哪里更改代码才能使我的程序再次运行? (注意:传递无效的短期选项时没问题)

这适用于命令行程序。它需要接收子命令作为其第一个参数和特定于每个子命令的选项。我想增加对长选项的支持,因为使用短选项非常困难。

char* subcommand = /* ... */;
int option_char = 0;
int exit_code = 0;

/* ... */
// Note: argv should be an array of strings containing the command-line arguments
int pm_parse_arguments(int argc, char** argv) {
    opterr = 0;
    if(strcmp(subcommand, "version") == 0) {
        return pm_parse_version_arguments(argc, argv);
    } else {
        // No recognized subcommand
        pm_global_unrecognized_subcommand(subcommand);
    }
    return exit_code;
}

int pm_parse_version_arguments(int argc, char** argv) {
    // List of long options
    struct option long_options[] = {
        {"help",        no_argument, 0, 'h'},
        {"major",       no_argument, 0, 'm'},
        {"minor",       no_argument, 0, 0},
        {"revision",    no_argument, 0, 'r'},
    };

    // Index of option
    int option_index = 0;

    while((option_char = getopt_long(argc, argv, ":hmr", long_options, &option_index)) != -1) {
        switch(option_char) {
            /* ... */
        }
    return exit_code;
}

当传递长选项Unrecognized option: --unknown时,它应该打印--unknown,就像短的选项一样。而是返回分段错误。

这是qbxswpoi的详细模式。

c++ pointers segmentation-fault
1个回答
1
投票

full output log of Valgrind要求使用归零选项结构终止长选项数组(类似于字符串以空值终止的方式)。否则,它不会知道有多少。

© www.soinside.com 2019 - 2024. All rights reserved.