[net.sources] minor bug in public-domain getopt

henry@utzoo.UUCP (Henry Spencer) (08/07/84)

One of the folks here has found a boundary-condition bug in the public-
domain getopt I posted to the net a while ago.  [This message is going
to net.cog-eng because that's one of the groups the original went to.]
It does not cope properly with the situation where a value-wanting option
is the very last argument, i.e. there is no value to give it.  The posted
code yields an optarg of NULL, which isn't necessarily acceptable.  To
fix, check the code near the end of getopt(3) from:

	if (*place == ':') {
		if (*scan != '\0') {
			optarg = scan;
			scan = NULL;
		} else {
			optarg = argv[optind];
			optind++;
		}
	}

to:

	if (*place == ':') {
		if (*scan != '\0') {
			optarg = scan;
			scan = NULL;
		} else if (optind < argc) {
			optarg = argv[optind];
			optind++;
		} else {
			fprintf(stderr, "%s: -%c argument missing\n", argv[0], c);
			return('?');
		}
	}

and recompile.  The getopt(1) program should be recompiled once this
fix is made.  The bug is probably not serious enough to justify massive
recompilations of existing software, since it's just bad handling of an
uncommon error.

Sorry about that, folks.
-- 
				Henry Spencer @ U of Toronto Zoology
				{allegra,ihnp4,linus,decvax}!utzoo!henry