strcpy_s :拷贝多少合适?

 

在VC2005之后,使用字符串拷贝函数strcpy会提示该函数不安全,将来会被抛弃类似这样的信息。所以一般都会改用

strcpy_s函数代替。

有时会出现这样的提示错误:“buffer is too small ……

 

代码示例:

 

char *str = "abcd"

char *des = new char [strlen(str)+1)];

 

strcpy_s(des,strlen(str),str);//提示错误……buffer is too small

 

 

errno_t strcpy_s(
   char *strDestination,
   size_t numberOfElements,
   const char *strSource
);

问题在于自己之前对函数的第二个参数理解有偏差。即size是谁的大小?

 

这个大小显然不能是目的空间的容纳大小,但是要满足 size <= size(dest);

这个大小也不能小于源内容的大小(上面示例即证明)。

因此这个大小应该是不小于源内容的大小(包括字符串的结束字符)。即 size(src) <= size <= size(dest) 

 

经过试验:如果size超过了dest的空间大小,并不会提示debug错误信息。如果小于src空间大小 则会提示上述的错误。

 

 

Remarks 说明
The strcpy_s function copies the contents in the address of strSource, including the terminating null

character, to the location specified by strDestination. The destination string must be large enough to

hold the source string, including the terminating null character. The behavior of strcpy_s is

undefined if the source and destination strings overlap.

 

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值