strcpy wars, jeez! A proposed resolution.

der Mouse mouse at mcgill-vision.UUCP
Tue Apr 12 19:24:47 AEST 1988


In article <6476 at dhw68k.cts.com>, david at dhw68k.cts.com (David H. Wolfskill) writes:
> Suppose, for example, that a given implementation defines that such a
> copy would be done from the beginning of the source string to its
> terminating NUL, character by character.  Then (assuming suitable
> definitions of the variables in question), an algorithm to clear a
> given string (str1) to a given value (other than NUL) could be coded:
> 	*str1 = ch;
> 	for (c1 = str1; *++c1 != '\0'; *c1 = *(c1 -1));

This will work even when ch *is* '\0'.  But it's subtly different from
what one would expect out of strcpy: this is equivalent to using a
strcpy that loops until it finds a null in the *destination* string,
not the *source* string.  (The way the same variable is used to refer
to both strings helps hide this fact.)

> or (remembering the characteristics of the implementation):
> 	*str1 = ch;
> 	strcpy(str1+1, str1)

This may well be an infinite loop, or rather, a
loop-until-memory-error.  For example, the canonical

strcpy(s1,s2) /* yes, I know this doesn't return anything */
register char *s1;
register char *s2;
{
 while (*s1++ = *s2++) ;
}

will scream off into higher and higher memory until it finds something
it can't read (or can't write, if that happens first) - or if it
doesn't find any such, as on a machine with a full complement of
memory, it will keep going forever.

Goodness, if even the advocates of completely-defined strcpy semantics
get confused about what it does, how can they expect anyone else to
keep it straight?

					der Mouse

			uucp: mouse at mcgill-vision.uucp
			arpa: mouse at larry.mcrcim.mcgill.edu



More information about the Comp.lang.c mailing list