Article View: comp.std.c
Article #2951Re: strcmp() on a non-nil-terminated string
From: John R. Levine
Date: Tue, 17 Nov 1992 04:53
Date: Tue, 17 Nov 1992 04:53
33 lines
1797 bytes
1797 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. ...
>> If so, can anyone imagine provide an example when this might happen?
Let's imagine a hypothetical CPU to which we'll give the made-up name of
Intel 80386DX-25. This CPU has an instruction to scan bytes at high speed
looking for a given byte value, and to compare two byte arrays stopping when
a byte that doesn't match is found. Both of these instructions take a
byte count to give the string length. So the fastest version of strcmp()
is roughly this:
scan arg1 for \0 to get its length, call it L
compare arg1,arg2, length L
Even though this looks at each byte of arg1 twice, it's considerably faster
than a loop because it uses the fast string instructions. If the arg1
argument isn't null-terminated, the initial scan could easily fly off the
end of the page causing various address faults.
Other machines with string scanning instructions, e.g. Vax and NS32032
would probably have strcmp() routines that'd fail the same way with
unterminated strings.
--
John R. Levine, IECC, POB 349, Cambridge MA 02238, +1 617 492 3869
johnl@iecc.cambridge.ma.us, {ima|spdcc|world}!iecc!johnl
"Time is Money! Steal some today!"
Technical Details
Message-ID:
<1992Nov17.045356.7973@iecc.cambridge.ma.us>Path:
arc1-ca.pugleaf.net!sparky!uunet!usc!sol.ctr.columbia.edu!eff!world!iecc!johnlReferences:
<1992Nov16.162313.3334@Urmel.Informatik.RWTH-Aachen.DE> <1992Nov16.224726.1258@sq.sq.com>Show Full Headers
Complete Article Headers
Newsgroups: comp.std.c Path: arc1-ca.pugleaf.net!sparky!uunet!usc!sol.ctr.columbia.edu!eff!world!iecc!johnl From: johnl@iecc.cambridge.ma.us (John R. Levine) Subject: Re: strcmp() on a non-nil-terminated string Organization: I.E.C.C. Date: Tue, 17 Nov 1992 04:53:56 GMT Message-ID: <1992Nov17.045356.7973@iecc.cambridge.ma.us> References: <1992Nov16.162313.3334@Urmel.Informatik.RWTH-Aachen.DE> <1992Nov16.224726.1258@sq.sq.com> Lines: 33