用memcpy_s用未签名的char替换memcpy

发布于 2025-02-12 05:02:20 字数 548 浏览 0 评论 0原文

假设我们有一个执行此操作的旧代码:

unsigned char* dest = new unsigned char[length];
memcpy(dest, source, length);

指针source作为该方法的输入参数传递。 长度是一个无符号的长变量。

现在,我想用它的安全版本替换被认为不安全的纪念呼叫,因此使用 memcpy_s 。 在其文档的基础上,此方法采用三个参数,即

  1. 目标
  2. 目标缓冲区的
  3. 大小,in memcpy_s的字节和WMEMCPY_S的宽字符(WCHAR_T)。来源
  4. 要复制的字符数。

我对第四参数有一些担忧。应该是这样的:

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,

  1. destination
  2. Size of the destination buffer, in bytes for memcpy_s and wide characters (wchar_t) for wmemcpy_s.
  3. the source
  4. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

删除→记忆 2025-02-19 05:02:20

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 sure source is not nullptr; all the other "security" checks are guaranteed to pass anyway:

  • The amount copied is the same as the destination size, no larger.
  • The destination is not nullptr - you just successfully allocated it.
  • If you were able to allocate length, then it can't be more than RSIZE_MAX.

That's it, no need to use memcpy_s().

Also, sizeof(unsigned char) is 1, necessarily.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文