用memcpy_s用未签名的char替换memcpy
假设我们有一个执行此操作的旧代码:
unsigned char* dest = new unsigned char[length];
memcpy(dest, source, length);
指针source
作为该方法的输入参数传递。 长度
是一个无符号的长变量。
现在,我想用它的安全版本替换被认为不安全的纪念呼叫,因此使用 memcpy_s 。 在其文档的基础上,此方法采用三个参数,即
- 目标
- 目标缓冲区的
- 大小,in memcpy_s的字节和WMEMCPY_S的宽字符(WCHAR_T)。来源
- 要复制的字符数。
我对第四参数有一些担忧。应该是这样的:
err = memcpy_s(dest, sizeof(dest), a2, length * sizeof (unsigned char));
是正确的吗?谢谢
Let's suppose we have a legacy code that performs this operation:
unsigned char* dest = new unsigned char[length];
memcpy(dest, source, length);
where the pointer source
is passed as input parameter of that method. length
is an unsigned long variable.
Now I want to replace the memcpy call, considered not secure, with the secure version of it, so with memcpy_s.
In base of its documentation, this method takes three parameters,
- destination
- Size of the destination buffer, in bytes for memcpy_s and wide characters (wchar_t) for wmemcpy_s.
- the source
- the number of characters to copy.
I'have some concern regarding the fourth parameter. Shall it be something like that:
err = memcpy_s(dest, sizeof(dest), a2, length * sizeof (unsigned char));
Is that correct? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
memcpy_s()
不是从根本上“更安全”。它只是执行A 很少的理智检查。就您而言,其中一些甚至是多余的。因此,如果要从无效的参数中“捍卫”您的函数实现,则可以确保source
不是nullptr
;所有其他“安全”检查都可以通过任何其他“安全性”检查:nullptr
- 您只是成功分配了它。长度
,则不能超过rsize_max
。就是这样,无需使用
memcpy_s()
。另外,
sizeof(unsigned char)
是1,一定要。memcpy_s()
is not fundamentally "more secure". It just performs a few sanity checks. In your case, some of these are even redundant. So, if you want to "defend" your function implementation from invalid arguments, you could make suresource
is notnullptr
; all the other "security" checks are guaranteed to pass anyway:nullptr
- you just successfully allocated it.length
, then it can't be more thanRSIZE_MAX
.That's it, no need to use
memcpy_s()
.Also,
sizeof(unsigned char)
is 1, necessarily.