1. strcpy 原型
char *strcpy(char *to, const char *from)
{
char *save = to;
for (; (*to = *from) != '/0'; ++from, ++to);
return(save);
}
from 源数据都来源于用户的输入,strcpy 是依据 /0 作为结束判断的,不做数据的检查,如果 to目标 的空间不够,则会引起 buffer overflow。
2. strncpy 比较安全一些。原型
char *strncpy(char *s1, const char *s2, size_t n);
在 ANSI C 中规定 n 并不是 sizeof(s1),而是要复制的 char 的个数。一个最常见的问题,就是 strncpy 并不帮你保证 /0 结束。
char buf[8];
strncpy( buf, "abcdefgh", 8 );
看这个程序,buf 将会被 "abcdefgh" 填满,但却没有 /0 结束符了。
另外,如果 s2 的内容比较少,而 n 又比较大的话,strncpy 将会把之间的空间都用 /0 填充。这又出现了一个效率上的问题,如下:
char buf[256];
strncpy( buf, "abcdefgh", 128 );此时 strncpy 会填写 128 个 char,而不仅仅是 "abcdefgh" 本身。
strncpy 的标准用法为:(手工写上 /0)
strncpy(path, src, sizeof(path) - 1);
path[sizeof(path) - 1] = '/0';
len = strlen(path);
3 memcpy 用来在内存中复制数据,由于字符串是以零结尾的,所以对于在数据中包含零的数据只能用memcpy。
memcpy
原型:extern void *memcpy(void *dest, void *src, unsigned int count);
用法:#include <string.h>
功能:由src所指内存区域复制count个字节到dest所指内存区域。
说明:src和dest所指内存区域不能重叠,函数返回指向dest的指针。
char *s="memcpy test";
char d[20];
memcpy(d,s,strlen(s));
d[strlen(s)]=0;
printf("%s",d);