Path: utzoo!mnetor!uunet!husc6!think!barmar From: barmar@think.COM (Barry Margolin) Newsgroups: comp.lang.c Subject: Re: strcpy Message-ID: <18582@think.UUCP> Date: 27 Mar 88 22:10:51 GMT References: <12636@brl-adm.ARPA> Sender: usenet@think.UUCP Reply-To: barmar@fafnir.think.com.UUCP (Barry Margolin) Organization: Thinking Machines Corporation, Cambridge, MA Lines: 64 In article <12636@brl-adm.ARPA> dsill@NSWC-OAS.arpa (Dave Sill) writes: ]In article <18488@think.UUCP> Barry Margolin writes: ]>Will you guys stop playing word games, and think about what that ]>sentence was really intended to mean? I think the point of the ]>"stopping after the NUL" phrase is that it doesn't copy any characters ]>after the NUL. Thus, if you have ]> ]> char [10] dest, source; ]> strcpy (source, "abcdefghi"); ]> strcpy (dest, "123456789"); ]> source [3] = '\0'; ]> strcpy (dest, source); ]> ]>the resulting contents of dest will be ]> ]> 'a' 'b' 'c' '\0' '5' '6' '7' '7' '9' '\0' ]> ]>i.e. the last six characters are not affected. ] ]I don't think that that's guaranteed, or even implied by that ]sentence. I would expect the contents of `dest' to be: ] ] 'a' 'b' 'c' '\0' ? ? ? ? ? ? ] ]where `?' may or may not be the same character that was in that ]position before the call to strcpy. I could imagine an implementation ]that would null-out the destination string if it was longer than the ]source. Well, I can't, because of C's rules about passing array arguments to functions. Only the address is passed, not the allocated length. If strcpy were to affect the portion of the destination array past the NUL character, it would have to be careful not to modify anything outside the destination array. But since it can't know where the destination array ends, it must not modify any elements but the ones necessary to perform its stated function (which, by the way, still doesn't prevent it from exceeding the destination's length -- it is the programmer's responsibility to make sure that sizeof(dest) > strlen(source)). ] ANSI describes `strcpy' a little differently: ] ] "The `strcpy' function copies the string pointed to by `s2' ] (including the terminating null character) into the array pointed ] to by `s1'. If copying takes place between objects that overlap, ] the behavior is undefined." ] ]There is nothing said about the order in which the copying takes ]place, or the contents of the destination string past the null ]character. There is also nothing said about the affect on /dev/icbm, but that doesn't imply that it is permitted to send it the "launch" signal. Since it doesn't say that the other elements of the destination are modified, I believe that an implementation would be incorrect if it did. And I suspect that there are many existing applications that assume that they can use strcpy to copy into the middle of a string without affecting later elements. Barry Margolin Thinking Machines Corp. barmar@think.com uunet!think!barmar