Pergunta

I noticed recently that some programs I have written (using libgetopt) segfault when given an argument starting with a double-dash e.g. --help.

I managed to reproduce this with the following small program:

#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;
}

When I compile and run this with ./a.out --help it works fine. But as soon as I compile using -O3 it segfaults. This behaviour is observed using Apple LLVM version 5.0 (clang-500.2.79) on OS X Mavericks (10.9).

Is there anything I can do to fix this, or should I just refrain from using -O3 in the future?

Foi útil?

Solução

From the man page for getopt_long

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

So what you need is another line

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

I suspected this was the case because I looked at your code and asked, "how does getopt_long know how many elements is in the array". man page confirmed.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top