Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.2 9/18/84; site sdcsvax.UUCP Path: utzoo!watmath!clyde!bonnie!akgua!sdcsvax!davidson From: davidson@sdcsvax.UUCP (Greg Davidson) Newsgroups: net.lang.c Subject: Re: Copy strings with "strcpy", not an idiom Message-ID: <741@sdcsvax.UUCP> Date: Sat, 16-Mar-85 02:21:55 EST Article-I.D.: sdcsvax.741 Posted: Sat Mar 16 02:21:55 1985 Date-Received: Sun, 17-Mar-85 02:25:22 EST References: <7042@watdaisy.UUCP> <7044@watdaisy.UUCP> <1040@mordor.UUCP> Distribution: net Organization: EECS Dept. U.C. San Diego Lines: 37 > 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)