home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #27 / NN_1992_27.iso / spool / comp / std / c / 3015 < prev    next >
Encoding:
Text File  |  1992-11-17  |  1.7 KB  |  44 lines

  1. Newsgroups: comp.std.c
  2. Path: sparky!uunet!usc!sol.ctr.columbia.edu!eff!world!iecc!johnl
  3. From: johnl@iecc.cambridge.ma.us (John R. Levine)
  4. Subject: Re: strcmp() on a non-nil-terminated string
  5. Organization: I.E.C.C.
  6. Date: Tue, 17 Nov 1992 04:53:56 GMT
  7. Message-ID: <1992Nov17.045356.7973@iecc.cambridge.ma.us>
  8. References: <1992Nov16.162313.3334@Urmel.Informatik.RWTH-Aachen.DE> <1992Nov16.224726.1258@sq.sq.com>
  9. Lines: 33
  10.  
  11. >> #include <string.h>
  12. >> char first[]="first";
  13. >> char second[]={'s','e','c','o','n','d'};
  14. >> main()
  15. >> { return!!strcmp(first,second); }
  16. >> Is this program allowed to behave undefined?
  17. >Yes. ...
  18. >> If so, can anyone imagine provide an example when this might happen?
  19.  
  20. Let's imagine a hypothetical CPU to which we'll give the made-up name of
  21. Intel 80386DX-25.  This CPU has an instruction to scan bytes at high speed
  22. looking for a given byte value, and to compare two byte arrays stopping when
  23. a byte that doesn't match is found.  Both of these instructions take a
  24. byte count to give the string length.  So the fastest version of strcmp()
  25. is roughly this:
  26.  
  27.     scan arg1 for \0 to get its length, call it L
  28.     compare arg1,arg2, length L
  29.  
  30. Even though this looks at each byte of arg1 twice, it's considerably faster
  31. than a loop because it uses the fast string instructions.  If the arg1
  32. argument isn't null-terminated, the initial scan could easily fly off the
  33. end of the page causing various address faults.
  34.  
  35. Other machines with string scanning instructions, e.g. Vax and NS32032
  36. would probably have strcmp() routines that'd fail the same way with
  37. unterminated strings.
  38.  
  39. -- 
  40. John R. Levine, IECC, POB 349, Cambridge MA 02238, +1 617 492 3869
  41. johnl@iecc.cambridge.ma.us, {ima|spdcc|world}!iecc!johnl
  42. "Time is Money!  Steal some today!"
  43.