String copy idiom -- warning about str[n]cpy

G A Moffett gam at amdahl.UUCP
Sat Mar 16 07:39:33 AEST 1985


I don't want to suggest that the "while (*s++ == *t++);" is
better than strcpy(s,t) [ I agree, let's use the library routines ]
but there is an instance where the 'idiom' is preferred:
if the string is being copied onto itself, for example:

	strcpy(s, s+5)  /* shift string 5 chars to the left */

This is NOT PORTABLE!  Many implimentations take advantage of
machine instructions to do string manipulation, and they will fail
(or act unpredictably, at least) if the target and source strings
overlap.  The SVR2 manual says under string(3C) "...overlapping
moves may yeild surprises."

So by all means use the librar routines instead of writing
"clever" routines yourself, but this is a case where the library
routine may not work in these peculiar cases.
-- 
Gordon A. Moffett		...!{ihnp4,hplabs,sun}!amdahl!gam



More information about the Comp.lang.c mailing list