strcpy wars, jeez! A proposed resolution.

John Gilmore gnu at hoptoad.uucp
Sun Mar 27 22:37:14 AEST 1988


In article <10731 at mimsy.UUCP> chris at mimsy.UUCP (Chris Torek) writes:
>		(void) strcpy(buf, buf + n);

gwyn at brl-smoke.ARPA (Doug Gwyn) wrote:
> 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
> through the source string...

I have seen plenty of constructs in traditional Unix and other C code
that assume strcpy() can slide a string down over itself.

While we are picking nits with the wording of various Unix man pages
and standards, let me point out that none of them makes it perfectly
clear that no bytes past the NUL are modified.  If you can assume that
"it copies the NUL and then stops" doesn't indicate that the NUL is
copied last, as several posters have done, you might as well assume
that it copies three or four more bytes beyond the NUL and then stops,
too.  It seems to make exactly as much sense to me, that is, no sense
at all.

I propose that strcpy, strncpy, strcat, and strncat be defined to perform
either:

  * left-to-right
or
  * non-destructively copying in the case of overlap

at the implementor's choice (each function can choose independently).
I think effectively 100% of the applications and 100% of the
implementations will require no change with this rule.  Simple
implementations will just do left-to-right, while more complicated
implementations like on the 29000 or MIPS can do fancy stuff 4 bytes at
a time, or even copy right-to-left, as long as they avoid destructive
copying.  Today's fancy implementations should already be checking for
overlap, since so much existing code depends on it.
-- 
{pyramid,ptsfa,amdahl,sun,ihnp4}!hoptoad!gnu			  gnu at toad.com
		"Watch me change my world..." -- Liquid Theatre



More information about the Comp.lang.c mailing list