2mac 2mac - 1 month ago 15
C Question

Segfault for invalid long option

I have the following code:

struct option longopts[] =
{
{"version", no_argument, 0, 'v'}
};

if (argc > 1)
{
int c;
int longindex;
while ((c = getopt_long (argc, argv, "v", longopts, &longindex)) != -1)
{
switch (c)
{
case 'v':
puts (VERSION_INFO);
exit (0);

case '?':
exit (1);
}
}
}


Why is it with an argument of
--versio
(intentionally misspelled) would cause a segfault but
-a
(which is also an invalid option) just prints an "invalid option" message to the screen?

Answer

You have to terminate the longopts array with an entry that is all zeros, otherwise getopt_long doesn't know when it ends. Your code is crashing because getopt_long is just iterating through random memory at that point because it has fallen off the end of longopts.

struct option longopts[] =
  {
    {"version", no_argument, NULL, 'v'},
    {NULL, 0, NULL, 0}
  };
Comments