🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c
Article #2949

Re: strcmp() on a non-nil-terminated string

#2949
From: Mark Brader
Date: Mon, 16 Nov 1992 22:47
48 lines
2267 bytes
> #include <string.h>
> char first[]="first";
> char second[]={'s','e','c','o','n','d'};
> main()
> { return!!strcmp(first,second); }
 
> Is this program allowed to behave undefined?

Yes.  Section 4.11.4.2 in the ANSI standard (7.11.4.2 in the ISO version)
specifies that the arguments of strcmp point to strings.  4.1.1 (7.1.1)
defines "string" (and what it means to point to one).  The array named
second does not contain a null character and therefore the pointer to
which it decays is not a valid argument to strcmp().  The result is
undefined behavior, as required by 4.1.6 (7.1.7).
 
> If so, can anyone imagine provide an example when this might happen?

Consider a hypothetical machine with a fast operation to compare blocks
of, say, 64 bytes, and another fast operation to scan forward up to a
certain number of bytes past a given address looking for a null byte.

Strcmp() might then be implemented like this:

	int strcmp (const char *s1, const char *s2)
	{
		for ( ; __no_nulls(s1, 64) && __no_nulls(s2, 64)
				&& __64_bytes_equal(s1, s2);
					s1 += 64, s2 += 64)
			;
		return __normal_strcmp(s1, s2);
	}

where __no_nulls() and __64_bytes_equal() each compile to a single
operation.  Then if the array named second is at the end of memory...
bang!

> You would expect a sane implementation to return with an exitcode of 1.

Well, I agree with this if the "sane implementation" is on what we would now
call a conventional computer.  However, I make no predictions as to what
sorts of computers will appear, let alone be conventional, in the future!
-- 
Mark Brader			"... one of the main causes of the fall of
SoftQuad Inc., Toronto		 the Roman Empire was that, lacking zero, they
utzoo!sq!msb			 had no way to indicate successful termination
msb@sq.com			 of their C programs."		-- Robert Firth

This article is in the public domain.
Technical Details
Message-ID: <1992Nov16.224726.1258@sq.sq.com>
Path: arc1-ca.pugleaf.net!sparky!uunet!uunet.ca!wildcan!sq!msb
References: <1992Nov16.162313.3334@Urmel.Informatik.RWTH-Aachen.DE>

Show Full Headers
Complete Article Headers
Newsgroups: comp.std.c
Path: arc1-ca.pugleaf.net!sparky!uunet!uunet.ca!wildcan!sq!msb
From: msb@sq.sq.com (Mark Brader)
Subject: Re: strcmp() on a non-nil-terminated string
Message-ID: <1992Nov16.224726.1258@sq.sq.com>
Organization: SoftQuad Inc., Toronto, Canada
References: <1992Nov16.162313.3334@Urmel.Informatik.RWTH-Aachen.DE>
Date: Mon, 16 Nov 92 22:47:26 GMT
Lines: 48