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

  1. Newsgroups: comp.std.c
  2. Path: sparky!uunet!uunet.ca!wildcan!sq!msb
  3. From: msb@sq.sq.com (Mark Brader)
  4. Subject: Re: strcmp() on a non-nil-terminated string
  5. Message-ID: <1992Nov16.224726.1258@sq.sq.com>
  6. Organization: SoftQuad Inc., Toronto, Canada
  7. References: <1992Nov16.162313.3334@Urmel.Informatik.RWTH-Aachen.DE>
  8. Date: Mon, 16 Nov 92 22:47:26 GMT
  9. Lines: 48
  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.  
  17. > Is this program allowed to behave undefined?
  18.  
  19. Yes.  Section 4.11.4.2 in the ANSI standard (7.11.4.2 in the ISO version)
  20. specifies that the arguments of strcmp point to strings.  4.1.1 (7.1.1)
  21. defines "string" (and what it means to point to one).  The array named
  22. second does not contain a null character and therefore the pointer to
  23. which it decays is not a valid argument to strcmp().  The result is
  24. undefined behavior, as required by 4.1.6 (7.1.7).
  25.  
  26. > If so, can anyone imagine provide an example when this might happen?
  27.  
  28. Consider a hypothetical machine with a fast operation to compare blocks
  29. of, say, 64 bytes, and another fast operation to scan forward up to a
  30. certain number of bytes past a given address looking for a null byte.
  31.  
  32. Strcmp() might then be implemented like this:
  33.  
  34.     int strcmp (const char *s1, const char *s2)
  35.     {
  36.         for ( ; __no_nulls(s1, 64) && __no_nulls(s2, 64)
  37.                 && __64_bytes_equal(s1, s2);
  38.                     s1 += 64, s2 += 64)
  39.             ;
  40.         return __normal_strcmp(s1, s2);
  41.     }
  42.  
  43. where __no_nulls() and __64_bytes_equal() each compile to a single
  44. operation.  Then if the array named second is at the end of memory...
  45. bang!
  46.  
  47. > You would expect a sane implementation to return with an exitcode of 1.
  48.  
  49. Well, I agree with this if the "sane implementation" is on what we would now
  50. call a conventional computer.  However, I make no predictions as to what
  51. sorts of computers will appear, let alone be conventional, in the future!
  52. -- 
  53. Mark Brader            "... one of the main causes of the fall of
  54. SoftQuad Inc., Toronto         the Roman Empire was that, lacking zero, they
  55. utzoo!sq!msb             had no way to indicate successful termination
  56. msb@sq.com             of their C programs."        -- Robert Firth
  57.  
  58. This article is in the public domain.
  59.