strncpy

Bill Poser poser at csli.Stanford.EDU
Wed Jan 24 10:08:04 AEST 1990


In article <25BC3A32.3F5B at marob.masa.com> daveh at 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 <stdio.h>
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.



More information about the Comp.lang.c mailing list