Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uwm.edu!ux1.cso.uiuc.edu!usenet From: bruner@sp15.csrd.uiuc.edu (John Bruner) Newsgroups: comp.sys.mac.programmer Subject: Re: Disinfectant 2.0 Sample Code Message-ID: <1990Jul16.153703.12982@ux1.cso.uiuc.edu> Date: 16 Jul 90 15:37:03 GMT References: <9510@accuvax.nwu.edu> <40562@think.Think.COM> <25571@cs.yale.edu> Sender: usenet@ux1.cso.uiuc.edu (News) Reply-To: bruner@sp15.csrd.uiuc.edu (John Bruner) Organization: CSRD, University of Illinois Lines: 55 In-Reply-To: tarr-michael@CS.YALE.EDU (michael tarr) In article <25571@cs.yale.edu>, tarr-michael@CS (michael tarr) writes: >Think C 4.01 also has a bug in strncpy: > >strncpy(s1, s2, 8); > >s1 will not have a '\0' appended to the end. So far as I can tell this >is not per the standard definition. > >Also sizeof returns an int, but malloc and calloc require size_t! This >is hidden on a none highlighted single line of text... Caused me great >pain to find this... Here's the ANSI definition (section 4.11.2.4 "The strncpy function", from the December 7, 1988 draft): #include char *strncpy(char *s1, const char *s2, size_t n) Description The strncpy function copies not more than n characters (characters that follow a null character are not copied) from the array pointed to by s2 to the array pointed to by s1.* If copying takes place between objects that overlap, the behavior is undefined. If the array pointed to by s2 is a string that is shorter than n characters, null characters are appended to the copy in the array pointed to by s1, until n characters in all have been written. Returns The strncpy function returns the value of s1. (footnote) Thus, if there is no null character in the first n characters of the array pointed to by s2, the result will not be null-terminated. This (essentially) has been the definition of strncpy() from its initial definition in UNIX (V7, I think, but my memory about this is a little hazy). This behavior comes from the original use for strncpy: filling fixed-length fields in UNIX data structures (e.g., 14-byte filenames in directory entries). Hence, it does not guarantee that the field will be null-terminated, but if it is too short, it may write more than one null character to fill out the destination. ANSI C (section 3.3.3.4) says that sizeof returns a value whose type is size_t. Thus, THINK C is not ANSI-compliant in its implementation of sizeof. This bug is very annoying, and I hope Symantec fixes it soon. -- John Bruner Center for Supercomputing R&D, University of Illinois bruner@csrd.uiuc.edu (217) 244-4476