CONFORMING TO
SVr4, 4.3BSD, C89, C99.
NOTES
Some programmers consider strncpy() to be inefficient and error prone.If the programmer knows (i.e., includes code
to test!) that the sizeof dest is greater than the length of src, then strcpy() can be used.
//一些程序考虑到strncpy()函数是没有效率的和倾向性的。如果程序知道目的代码的大小等于源代码的长度,那么这个strcpy()函数
就会被使用。
If there is no terminating null byte in the first n characters of src,strncpy() produces an unterminated string in dest.
Programmers often prevent this mistake by forcing termination as follows:
//如果在源代码的n个自符中没有结束的空字节,那么strncpr()函数在目的代码中也不 会产生一个结束字符串。程序总是通过
强迫终止来阻止这个错误。如下:
strncpy(buf, str, n);
if (n > 0)
buf[n - 1]= '\0';
BUGS
If the destination string of a strcpy() is not large enough, then any-thing might happen. Overflowing
fixed-length string buffers isa favorite cracker technique for taking complete control of the machine.Any time a
program reads or copies datainto a buffer, the programfirst needs to check that there’s enough space. This may be
unneces-sary if you can show that overflow is impossible, but be careful: programscan get changed over time, in ways that may make
the impossible possible.
//如果strcpy()函数的结束字符串不是足够大,就会发生一些问题。固定长度 的字符串溢出缓冲区是一个完成控制机器好的一个
技能。有时候一个程序在缓冲区读或者复制数据,这个程序首先需要去检查空间是否足够大。溢出是可能的,但是要仔细:程序能
够及时的改变,用这种方式上使之成为可能。
SEE ALSO
bcopy(3), memccpy(3), memcpy(3), memmove(3), strdup(3), stpcpy(3),
wcscpy(3), wcsncpy(3)
COLOPHON
This page is part of release 3.22 of the Linux man-pages project. Adescription of the project, and information about
reporting
bugs, can be found at
//这篇是linux3.2版本中手册项目的一部分。一个项目的描述,还有关于信息漏洞的报告,
能够在中找到。
GNU 2009-06-01 STRCPY(3)
(END)
例:
-
#include <stdio.h>
-
#include <string.h>
-
-
char *mystrcpy(char *dest, char *src)
-
{
-
int i=0;
-
while(1)
-
{
-
dest[i]=src[i];
-
if(src[i] == '\0')
-
break;
-
i++;
-
}
-
}
-
-
int main()
-
{
-
char s1[13]="nihao shijie";
-
char s2[9]="hello hi";
-
-
//先打印s2的字符串
-
printf("s2 is: %s\n", s2);
-
-
//mystrcpy(s2,s1);
-
-
//从s1中复制8个字符到s2中
-
strncpy(s2,s1,8);
-
-
//再打印复制后s2的字符串
-
printf("s2 is: %s\n", s2);
-
-
return 0;
-
}