strncpy

Bill Poser poser at csli.Stanford.EDU
Wed Jan 24 10:41:03 AEST 1990


	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 <stdio.h>
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.



More information about the Comp.lang.c mailing list