Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getopt_long_only segmentation fault

I'm trying to use getopt_long_only to parse a command line. My app reads a handful of command line options.

E.g. "app --alpha=1 --beta=2 --cecil=3"

getopt_long_only works fine as expected as long as valid command line parameters are passed in. But if you invoke the app with an invalid "single dashed" option at the end and at other inappropriate places, a seg fault crash occurs. What's going on here? Seems like getopt_long_only isn't being resilient to mistyped arguments. Or am I invoking the function wrong?

Example:

> ./app --beta=1 -?
starting
index = 1   ret=0  optarg=1
Segmentation fault

Code below (C++: app.cc)

#include <stdio.h>
#include <getopt.h>

void ProcessCommandLineArgs(int argc, char** argv)
{

    option longopts[] = {
        {"alpha", optional_argument, 0, 0},
        {"beta",  optional_argument, 0, 0},
        {"cecil", optional_argument, 0, 0}
    };

    int index;
    int ret;
    bool fParseError = false;

    while (true)
    {
        ret = ::getopt_long_only(argc, argv, "", longopts, &index);

        if (ret < 0)
        {
            break;
        }

        if ((ret == '?') || (ret == ':'))
        {
            fParseError = true;
            break;
        }

        printf("index = %d   ret=%d  optarg=%s\n", index, ret, optarg?optarg:"<null>");
    }
}

int main(int argc, char** argv)
{
    printf("starting\n");
    ProcessCommandLineArgs(argc, argv);
    printf("exiting\n");
    return 0;
}
like image 913
selbie Avatar asked Jul 18 '11 04:07

selbie


1 Answers

I found the problem.

I was forgetting to have a "zero-row" at the end of my option array declaration.

option longopts[] = {
    {"alpha", optional_argument, 0, 0},
    {"beta",  optional_argument, 0, 0},
    {"cecil", optional_argument, 0, 0},
    {NULL, 0, 0, 0}
};
like image 102
selbie Avatar answered Oct 21 '22 12:10

selbie