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;
}
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}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With