strcpy(),strncpy()
来源:互联网 发布:mac rvm 安装ruby 慢 编辑:程序博客网 时间:2024/05/18 00:15
1. strcpy
我们知道,strcpy 是依据\0作为结束判断的,如果 to 的空间不够,则会引起 buffer overflow。strcpy 常规的实现代码如下(来自 OpenBSD 3.9):
char *
strcpy(char *to, const char *from)
{
char *save = to;
for (; (*to = *from) != ''; ++from, ++to);
return(save);
}
但通常,我们的 from 都来源于用户的输入,很可能是非常大的一个字符串,因此 strcpy 不够安全。
2. strncpy
在 ANSI C 中,strcpy 的安全版本是 strncpy。
char *strncpy(char *s1, const char *s2, size_t n);
但 strncpy 其行为是很诡异的(不符合我们的通常习惯)。标准规定 n 并不是 sizeof(s1),而是要复制的 char 的个数。一个最常见的问题,就是 strncpy 并不帮你保证 结束。
char buf[8];
strncpy( buf, "abcdefgh", 8 );
看这个程序,buf 将会被 "abcdefgh" 填满,但却没有 结束符了。
另外,如果 s2 的内容比较少,而 n 又比较大的话,strncpy 将会把之间的空间都用 填充。这又出现了一个效率上的问题,如下:
char buf[80];
strncpy( buf, "abcdefgh", 79 );
上面的 strncpy 会填写 79 个 char,而不仅仅是 "abcdefgh" 本身。
strncpy 的标准用法为:(手工写上 )
strncpy(path, src, sizeof(path) - 1);
path[sizeof(path) - 1] = '';
len = strlen(path);
- strcpy & strncpy
- Strcpy / Strncpy
- strcpy(),strncpy()
- strcpy & strncpy
- strncpy strcpy
- strcpy 和 strncpy
- strcpy,strncpy,strlcpy,memcpy
- strcat/strncpy/strcpy
- strcpy, strncpy and strlcpy
- strcpy和strncpy区别
- memcpy, strncpy, strcpy
- 深入理解strcpy,strncpy
- strcpy,strncpy,strlcpy,memcpy
- strcpy strcpy_s strncpy
- Strcpy和Strncpy
- 深入理解strcpy,strncpy
- strcpy/strncpy/strcpy_s比较
- strcpy和strncpy区别
- int main():声明指定了两个以上的数据类型
- 大众点评网笔试总结
- Response中文乱码问题
- JSP SERVLET编码总结
- MFC构架中文档数据的读取和显示(未完)
- strcpy(),strncpy()
- Win7下如何访问Local Settings等拒绝访问的文件夹?
- STL
- web中文乱码问题
- 7.7 introduce foreign method(引入外加函数)
- VC下的小工具
- 文件上传与参数乱码
- C++ STL学习之list
- vs.net环境下的C++编程