strcpy_s :拷贝多少合适?

来源:互联网 发布:mac 修改登录用户密码 编辑:程序博客网 时间:2024/03/28 19:26

 

在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.

 

 

原创粉丝点击