This is the mail archive of the libc-help@sourceware.org mailing list for the glibc project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Bug in getopt_long under specific circumstances when non-options present


Hello list,

I believe I have found a bug in getopt_long which manifests itself only 
in very specific situations when non-options are present in argv.

If you run the included small program (see below) as follows: 

$ ./test create --set=test test --invalid
--set
./test: unrecognized option '--invalid'
bad long opt "test"

... you can see getopt_long correctly identifies `--invalid' as not being 
a valid long option (./test: unrecognized option '--invalid') but `optind' 
doesn't seem to be set correctly which results in the output of the wrong 
option by the test program (bad long opt "test").

I haven't had a look in libc's source code but it seems that `optind' is 
indeed set wrongly under very specific circumstances unless I'm wrong. 

Can someone confirm this?


-- test program follows --

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

int main(int argc, char **argv)
{
  struct option longopts[] = {
    { "set", optional_argument, NULL, 'S' },
    { NULL, 0, NULL, 0 }
  };
  
  int c;

  do {
    int curind = optind;
    c = getopt_long(argc, argv, "s::", longopts, NULL);
    
    switch (c) {
    case 's':
      printf("-s\n");
      break;
      
    case 'S':
      printf("--set\n");
      break;
      
    case '?':
      if (optopt)
        printf("bad short opt '%c'\n", optopt);
      else
        printf("bad long opt \"%s\"\n", argv[curind]);
      break;
      
    case -1:
      break;
      
    default:
      printf("returned %d\n", c);
      break;
    }
  } while (c != -1);

  return 0;
}



-- 
Miguel


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]