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: <11882@csli.Stanford.EDU> Date: 23 Jan 90 23:41:03 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> <11881@csli.Stanford.EDU> 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: 48 As a further clarification of what strncpy(3) actually does, let me point out that although it only COPIES up to the null byte in the source string, it WRITES exactly N characters into the target string, padding with nulls if necessary. So the bit about null-padding in the manual is correct - what is erroneous is the bit about copying. To see this, try a program like this: #include main() { char src[20]; char tgt[20]; sprintf(src,"%s","abcdefg"); sprintf(tgt,"%s","abcdefg"); printf("src = %s\n",src); printf("tgt = %s\n",tgt); src[3] = '\0'; printf("src = %s\n",src); strncpy(tgt,src,5); printf("tgt = %s\n",tgt); printf("tgt[4] = %c\n",tgt[4]); printf("tgt[5+] = %s\n",&(tgt[5])); exit(0); } It initializes both src and tgt to "abcdefg", assigns a null to src[3], does the strncpy, and then prints the various pieces of tgt. The result is: Script started on Tue Jan 23 15:34:49 1990 crystals-[1]/user2/poser : foo src = abcdefg tgt = abcdefg src = abc tgt = abc tgt[4] = tgt[5+] = fg crystals-[2]/user2/poser : script done on Tue Jan 23 15:34:57 1990 Notice that the fifth character of tgt, originally "e", has been overwritten by a null, but that the remainder of tgt is unaffected. So, what strncpy does is to COPY up to the null byte or N characters, whichever comes first, and then null-pad out to the N character limit.