Home > Net >  Replace memcpy with memcpy_s with an unsigned char
Replace memcpy with memcpy_s with an unsigned char

Time:07-09

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

CodePudding user response:

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.

  • Related