From mboxrd@z Thu Jan 1 00:00:00 1970 X-Msuck: nntp://news.gmane.org/gmane.linux.lib.musl.general/6381 Path: news.gmane.org!not-for-mail From: Felix Fietkau Newsgroups: gmane.linux.lib.musl.general Subject: [PATCH v2] getopt: fix optional argument processing Date: Tue, 21 Oct 2014 22:24:50 +0200 Message-ID: <1413923090-71355-1-git-send-email-nbd@openwrt.org> Reply-To: musl@lists.openwall.com NNTP-Posting-Host: plane.gmane.org X-Trace: ger.gmane.org 1413923114 23491 80.91.229.3 (21 Oct 2014 20:25:14 GMT) X-Complaints-To: usenet@ger.gmane.org NNTP-Posting-Date: Tue, 21 Oct 2014 20:25:14 +0000 (UTC) To: musl@lists.openwall.com Original-X-From: musl-return-6394-gllmg-musl=m.gmane.org@lists.openwall.com Tue Oct 21 22:25:07 2014 Return-path: Envelope-to: gllmg-musl@plane.gmane.org Original-Received: from mother.openwall.net ([195.42.179.200]) by plane.gmane.org with smtp (Exim 4.69) (envelope-from ) id 1XgfzM-0003LH-Tt for gllmg-musl@plane.gmane.org; Tue, 21 Oct 2014 22:25:05 +0200 Original-Received: (qmail 20147 invoked by uid 550); 21 Oct 2014 20:25:02 -0000 Mailing-List: contact musl-help@lists.openwall.com; run by ezmlm Precedence: bulk List-Post: List-Help: List-Unsubscribe: List-Subscribe: Original-Received: (qmail 20128 invoked from network); 21 Oct 2014 20:25:01 -0000 X-Mailer: git-send-email 2.0.4 Xref: news.gmane.org gmane.linux.lib.musl.general:6381 Archived-At: Processing an option character with optional argument fails if the option is last on the command line. This happens because the if (optind >= argc) check runs first before testing for optional argument. --- src/misc/getopt.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/misc/getopt.c b/src/misc/getopt.c index 8a2e4d5..f94c4f7 100644 --- a/src/misc/getopt.c +++ b/src/misc/getopt.c @@ -55,7 +55,8 @@ int getopt(int argc, char * const argv[], const char *optstring) return '?'; } if (optstring[i+1] == ':') { - if (optind >= argc) { + if (optstring[i+2] == ':') optarg = 0; + else if (optind >= argc) { if (optstring[0] == ':') return ':'; if (opterr) { write(2, argv[0], strlen(argv[0])); @@ -65,7 +66,6 @@ int getopt(int argc, char * const argv[], const char *optstring) } return '?'; } - if (optstring[i+2] == ':') optarg = 0; if (optstring[i+2] != ':' || optpos) { optarg = argv[optind++] + optpos; optpos = 0; -- 2.0.4