别再耍流氓了: 请别再用strcpy, 而用strncpy 或stpcpy, strlcpy (linux)

 我们先来看看strcpy, 下面的程序没有问题:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. int main()  
  5. {  
  6.     char str[4] = {0};  
  7.     char *p = "abc";  
  8.     strcpy(str, p);  
  9.     cout << str << endl;  
  10.   
  11.     return 0;  
  12. }  

      但是,我运行下面程序的时候,就有问题了:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. int main()  
  5. {  
  6.     char str[4] = {0};  
  7.     char *p = "abcdefg";  
  8.     strcpy(str, p);  
  9.     cout << str << endl;  
  10.   
  11.     return 0;  
  12. }  
     结果如下:

       也许你要说, 这是程序猿不小心, str的空间太小, p指向的串太大,程序猿小心注意一下就好了。真的是这样吗?马虎的程序猿还少吗?反正,我有时也是马虎程序猿之一。谁也不敢保证自己在用strcpy的时候,str的空间足够大。 你想,系统那么复杂, p指向的串,有时你根本无法预料,对不对? 所以,要避免这类程序崩溃,不能仅仅依赖于程序猿的细心和认真,尽管我们可以尽可能细心。


      那怎么办?我们看看更安全的strncpy函数吧,原型:char *strncpy(char *dest, char *src, size_t num);

上述有问题的程序应该改为:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. int main()  
  5. {  
  6.     char str[4] = {0};  
  7.     char *p = "abcdefg";  
  8.     strncpy(str, p, sizeof(str) - 1);  
  9.     cout << str << endl;  
  10.   
  11.     return 0;  
  12. }  
      或许,你要说, 上面这样拷贝后, str中得到的不是想要的"abcdefg"啊!对,但这样至少不会导致系统崩溃。最后的问题是:系统不崩溃,但串不对,这样就相对好定位了。


另外看一下下面这个小程序:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. int main()  
  5. {  
  6.     char str[4] = {0};  
  7.     char *p = "a\0bcdefg";  
  8.     strncpy(str, p, sizeof(str) - 1);  
  9.     cout << str << endl;  
  10.   
  11.     return 0;  
  12. }  
     结果为a


绝对绝对要注意的是: strncpy并没有拷贝串后的\0字符,而strcpy却拷贝了。这充分说明,strncpy是为拷贝字符而生的,而strcpy是拷贝字符串而生的。但两者都不能越界拷贝。只要正确使用strncpy, 那就比strcpy安全。

看看这个程序:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. int main()  
  5. {  
  6.     char str[4] = "xyz";  
  7.     str[3] = 'w'//故意将最后的\0换成w  
  8.       
  9.     char *p = "abc";  
  10.     strcpy(str, p); //把p指向的串拷贝到str中去(刚好可以容纳)  
  11.     cout << str << endl;  
  12.   
  13.     return 0;  
  14. }  
      结果为:abc

再看:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. int main()  
  5. {  
  6.     char str[4] = "xyz";  
  7.     str[3] = 'w'//故意将最后的'\0'换成'w'  
  8.       
  9.     char *p = "abc";  
  10.     strncpy(str, p, sizeof(str) - 1); //只拷贝了3个字符,没有拷贝'\0'  
  11.     cout << str << endl;  
  12.   
  13.     return 0;  
  14. }  
     结果为: abcw? 异常的结果,当然,在你的机器上很可能是其他的异常结果。 从这个例子可以看出, 定义str的时候,如果不进行初始化(char str[4] = {0};),那是非常非常危险的!


总结一下:

1. 好的程序猿用strncpy, 先定义并初始化char str[MAX + 1] = {0};, 如果在程序中间需要再往str中拷贝串,一定要用memset清零。 拷贝范式为:strncpy(str, p, sizeof(str) - 1); , 流氓程序猿用strcpy, 当然我经常在写博客时这么干.

2. strncpy拷贝的是字符,不拷贝串,所以最后一个\0没有拷贝,所以,拷贝的时候需要对串进行清零处理,一定要养成好习惯。

3. strncpy拷贝时,可能会导致截断,但程序不会崩溃。

4. 根据上面strncpy的原型,其实strncpy也并不一定拷贝num个字符,有特殊情况,比如:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. int main()  
  5. {  
  6.     char str[4] = {'w''x''y''z'};  
  7.     char *p = "a\0bcdefg";  
  8.     strncpy(str, p, sizeof(str) - 1);  
  9.   
  10.     cout << int(str[0]) << endl; // 'a'  
  11.     cout << int(str[1]) << endl; // '\0'  
  12.     cout << int(str[2]) << endl; // '\0'   //确实要注意这个值, 不是'b'  
  13.   
  14.     cout << int(str[3]) << endl; // 'z'  
  15.   
  16.     return 0;  
  17. }  


5(后来补充的)用strncpy的时候, 要防止内存重叠。


from : http://www.linuxidc.com/Linux/2012-06/61893.htm

strcpy ,strncpy ,strlcpy的用法

好多人已经知道利用strncpy替代strcpy来防止缓冲区越界。

但是如果还要考虑运行效率的话,也许strlcpy是一个更好的方式。

1. strcpy

strcpy 是依据 /0 作为结束判断的,如果 to 的空间不够,则会引起 buffer overflow。strcpy 常规的实现代码如下(来自 OpenBSD 3.9):

char * strcpy(char *to, const char *from)

{

       char *save = to;

 

       for (; (*to = *from) != '/0'; ++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 并不帮你保证 /0

结束。

char buf[8];

strncpy( buf, "abcdefgh", 8 );

看这个程序,buf 将会被 "abcdefgh" 填满,但却没有 /0 结束符了。

另外,如果 s2 的内容比较少,而 n 又比较大的话,strncpy 将会把之间的空间都用 /0 填充。这又出现了一个效率上的问题,如下:

char buf[80];

strncpy( buf, "abcdefgh", 79 );

上面的 strncpy 会填写 79 个 char,而不仅仅是 "abcdefgh" 本身。

strncpy 的标准用法为:(手工写上 /0)

strncpy(path, src, sizeof(path) - 1);

path[sizeof(path) - 1] = '/0';

len = strlen(path);

3. strlcpy

// Copy src to string dst of size siz. At most siz-1 characters

// will be copied. Always NUL terminates (unless siz == 0).

// Returns strlen(src); if retval >= siz, truncation occurred.

size_t   strlcpy(char *dst, const char *src, size_t siz);

而使用 strlcpy,就不需要我们去手动负责 /0 了,仅需要把 sizeof(dst) 告之 strlcpy 即可:

strlcpy(path, src, sizeof(path));

len = strlen(path);

if ( len >= sizeof(path) )

       printf("src is truncated.");

并且 strlcpy 传回的是 strlen(str),因此我们也很方便的可以判断数据是否被截断。

[* 一点点历史 *]

strlcpy 并不属于 ANSI C,至今也还不是标准。

strlcpy 来源于 OpenBSD 2.4,之后很多 unix-like 系统的 libc 中都加入了 strlcpy 函数,我个人在 FreeBSD、Linux 里面都找到了 strlcpy。(Linux使用的是 glibc,

glibc里面有 strlcpy,则所有的 Linux 版本也都应该有 strlcpy)

但 Windows 下是没有 strlcpy 的,对应的是strncpy和memset函数


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值