Reputation: 143
Optarg is always null. Application crashes.
static const char* const short_options = "a:h:p";
static const struct option long_options[] =
{
{ "address", 1, NULL, 'a' },
{ "help", 0, NULL, 'h' },
{ "port", 1, NULL, 'p' }
};
I tried to add null string to the long_options, but it did not help.
static const struct option long_options[] =
{
{ "address", 1, NULL, 'a' },
{ "help", 0, NULL, 'h' },
{ "port", 1, NULL, 'p' },
{0, 0, NULL, 0 }
};
but it did not help.
There is example of the optarg using. I use optarg with the same way, but get null.
do {
nextOption = getopt_long(argc, argv, short_options, long_options, NULL);
switch (nextOption)
{
case 'a':
{
//do something
}
break;
case 'h':
printf(usage_template);
exit(0);
case 'p':
{
long value;
char* end;
value = strtol(optarg, &end, 10);//OPTARG IS NULL
if (*end != '\0')
{
printf(usage_template);
}
port = (uint16_t)htons(value);
}
break;
case '?':
printf(usage_template);
exit(0);
case -1:
break;
default:
exit(0);
}
} while (nextOption != -1);
Can anybody help me with this issue?
Upvotes: 1
Views: 1021
Reputation: 360
It looks like your "p" option isn't followed by a colon, so getopt isn't expecting it to have an argument.
Upvotes: 6