strcpy

John Woods, Software john at frog.UUCP
Tue Mar 29 10:48:00 AEST 1988


In article <1304 at ut-emx.UUCP>, wca at ut-emx.UUCP (William C. Anderson) writes:
> In article <10753 at mimsy.UUCP>, chris at mims
y.UUCP (Chris Torek) writes:
> -> In article <7506 at brl-smoke.ARPA> gwyn at brl-smoke.ARPA (Doug Gwyn) writes:
> -> ->This usage was never a good idea, because a valid implementation of
> -> ->strcpy() would be to copy right-to-left rather than left-to-right
> -> `That turns out not to be the case'---or rather, are you certain?
> Chris is right here, Doug.  For example, the ndbm(3) routines in 4.3BSD
> depend upon bcopy() doing the correct ordering in cases of overlap.
> Luckily, it is simple to do the code correctly.

BUZZ!  No, Doug is right.  The standard (3 August 87 draft) explicitly
states that "If copying takes place between objects that overlap, the
behavior is undefined."  You can't *depend* on the behavior of strcpy()
and expect to have your program be portable, QED.  Perhaps bcopy() is
*defined* to work correctly in cases of overlap, though people worried about
that less back in the old days :-).

The following is a perfectly *legal* (if perfectly awful) implementation.

char *strcpy(char *s1, const char *s2)
{
	const char *eos = s2 + strlen(s2);
	s1 += strlen(s2);
	while (eos != s2) *s1-- = *eos--;
	*s1 = *eos;
	return s1;
}

--
John Woods, Charles River Data Systems, Framingham MA, (617) 626-1101
...!decvax!frog!john, ...!mit-eddie!jfw, jfw at eddie.mit.edu

FUN:  THE FINAL FRONTIER
Zippy the Pinhead in '88!



More information about the Comp.lang.c mailing list