Copy strings with "strcpy", not an idiom
Greg Davidson
davidson at sdcsvax.UUCP
Sat Mar 16 17:21:55 AEST 1985
> The most portable, most readable, and often most efficient way
> to copy strings is to use the string copying routines.
> --
> John Bruner (S-1 Project, Lawrence Livermore National Laboratory)
Unfortunately, the string copy routines in the standard library are
neither safe nor convenient. strcpy is only usable if you KNOW that
overrunning is impossible. strncpy is totally unusable because if
overrunning occurs, it may not nul terminate the destination, and
no indication is returned to allow detection of this event.
Note that the standard idiom suffers from the same insecurity as
strcpy. And yes, I frequently encounter software which bombs because
of this, because it just assumed that filenames, etc. would be no
longer than N bytes. Idioms are always dangerous when applied to
overrunnable or overflowable objects, because checking for these
cases always spoils the prettiness of the idiom, so programmers
don't do it.
My solution is to use my own string routines, which always take the
maximum length of the destination string as a parameter (note that
the standard strncat wants the amount of room LEFT in dst, which
usually must be calculated), and always return the number of
characters lost (if any) through truncation.
scopy(dst, room, src) scat(dst, room, src)
char *dst, *src; char *dst, *src;
int room; int room;
{ {
/* Assert( room > 0 ) */ int l = strlen(dst);
while (--room && *src)
*dst++ = *src++; return scopy( dst + l,
*dst = '\0'; room - l,
return strlen(src); src );
} }
_Greg Davidson (Virtual Infinity Systems, San Diego)
More information about the Comp.lang.c
mailing list