getopt(): Is optarg guaranteed to be non-NULL if optstring contains something like "a:"?

StackOverflow https://stackoverflow.com/questions/20647990

  •  19-09-2022
  •  | 
  •  

Question

When I am writing a piece of code, say something like this:

int i_flag;
char *s;
while ((c = getopt (argc, argv, "i::o:")) != -1) // I know "i::" is a GNU extension
    switch (c) {
    case 'i':
        i_flag = 1;
        if (optarg != NULL)
            str-i = optarg;
        break;
    case 'o':
        id = strtol (optarg, &s, 0);
        if (id < 0 || id > 5 || *s) {
            fprintf(stderr, "Invalid ID: %s\n", optarg);
            print_usage(); // this function exit()'s the program
        }
        break;
    default:
        print_usage();
    }

My question is that I know optarg can be NULL in the 'i' case, but can it be NULL in the 'o' case? I think it should not be NULL at all, but it does not seem to be guaranteed in POSIX.

I have this question since a very smart static analyzer looks at if (optarg != NULL) and says "Oh, so optarg can be NULL and you didn't check it in case 'o'.

Update: Fix int i-flag;.

Était-ce utile?

La solution

Yes, optarg will be non-null. If a argument is omitted for an option that requires one, getopt will return '?'.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top