Fix optind handling inconsistency in getopt_long() for missing argument

From: Japin Li <japinli(at)hotmail(dot)com>
To: PostgreSQL-development <pgsql-hackers(at)lists(dot)postgresql(dot)org>
Subject: Fix optind handling inconsistency in getopt_long() for missing argument
Date: 2026-07-21 10:16:27
Message-ID: SY7PR01MB10921AF81F18A8BCFA06388BEB6C22@SY7PR01MB10921.ausprd01.prod.outlook.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers


Hi, hackers

I noticed an inconsistency in how optind is handled when a required argument
is missing.

For short options, the current code handles the BADARG case as follows:

else if (argc <= ++optind)
{ /* no arg */
place = EMSG;
if (*optstring == ':')
return BADARG;
if (opterr)
fprintf(stderr,
"%s: option requires an argument -- %c\n",
argv[0], optopt);
return BADCH;
}

Here, place is set to EMSG and optind is incremented before returning BADARG.
However, for long options, the same logic currently sets place = EMSG and
increments optind after returning BADARG.

else
{
if (optstring[0] == ':')
return BADARG; <-- here, return before increasing optind

if (opterr && has_arg == required_argument)
fprintf(stderr,
"%s: option requires an argument -- %s\n",
argv[0], place);

place = EMSG;
optind++;

if (has_arg == required_argument)
return BADCH;
optarg = NULL;
}

The attached patch moves the place = EMSG and optind++ assignments to the
beginning of the long‑option error block, aligning the behavior with that of
short options.

Any thought?

--
Regards,
Japin Li
ChengDu WenWu Information Technology Co., Ltd.

Attachment Content-Type Size
v1-0001-Fix-optind-handling-inconsistency-in-getopt_long-.patch text/x-patch 1.0 KB

Browse pgsql-hackers by date

  From Date Subject
Next Message Nitin Jadhav 2026-07-21 10:47:17 Re: Change checkpoint‑record‑missing PANIC to FATAL
Previous Message Ajin Cherian 2026-07-21 10:16:13 Re: [PATCH] Preserve replication origin OIDs in pg_upgrade