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,
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
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:
nullptr
- you just successfully allocated it.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.