Path: utzoo!utgpu!jarvis.csri.toronto.edu!cs.utexas.edu!swrinde!zaphod.mps.ohio-state.edu!uakari.primate.wisc.edu!ames!decwrl!shelby!csli!poser From: poser@csli.Stanford.EDU (Bill Poser) Newsgroups: comp.lang.c Subject: Re: strncpy Message-ID: <11881@csli.Stanford.EDU> Date: 23 Jan 90 23:08:04 GMT References: <11527@csli.Stanford.EDU> <000003Q@cdis-1.UUCP> <11616@csli.Stanford.EDU> <48314938.f69e@phobos.UUCP> <11864@csli.Stanford.EDU> <25BC3A32.3F5B@marob.masa.com> Sender: poser@csli.Stanford.EDU (Bill Poser) Reply-To: poser@csli.stanford.edu (Bill Poser) Organization: Center for the Study of Language and Information, Stanford U. Lines: 52 In article <25BC3A32.3F5B@marob.masa.com> daveh@marob.masa.com (Dave Hammond) writes: >From the Xenix manual page for string(S): > >char *strncpy(S1,S2,N) >... >strncpy copies exactly N characters, truncating or null-padding S2; the >target may not be null-terminated if the length of S2 is N or more. The manual page does indeed say that strncpy(3) copies exactly N characters, but as William Davidsen has pointed out, the manual, at least on some systems, is wrong. Here is a little test program. #include main() { char src[20]; char tgt[20]; sprintf(src,"%s","abcdefg"); printf("src = %s\n",src); src[3] = '\0'; printf("src = %s\n",src); strncpy(tgt,src,5); printf("tgt = %s\n",tgt); exit(0); } It puts the string "abcdefg" (7 characters plus a null) into src and prints it out. Then it assigns a null to the 4th position, overwriting the "d" and prints it out. Then it strncpy's it to tgt, requesting a 5 character copy, and prints the result. I just compiled and ran this program on: (a) a SUN 4 running SUN-OS; (b) an HP 9000/350 running HP-UX, and (c) an HP 9000/320 running 4.3 Tahoe BSD. On all three the result was that the null byte terminated the copy. Here is the script from the HP 350: Script started on Tue Jan 23 14:58:27 1990 crystals-[1]/user2/poser : foo src = abcdefg src = abc tgt = abc crystals-[2]/user2/poser : script done on Tue Jan 23 14:58:33 1990 If strncpy copied exactly N characters, the third output line should read: tgt = abcde On all three systems the manual says that strncpy copies exactly N characters, and on all three it is wrong.