As some of you may know, Microsoft banned memcpy() from their Security Development Lifecycle, replacing it with memcpy_s().
void *memcpy(void *dest, const void *src, size_t n);
/* simplified signature */
errno_t memcpy_s(void *dst, size_t dstsize, const void *src, size_t n);
So if your code used to be:
if (in_len > dst_len) {
/* error */
}
memcpy(dst, src, in_len);
it becomes:
if (memcpy_s(dst, dst_len, src, src_len)) {
/* error */
}
Or, with truncation,
memcpy(dst, src, min(in_len, dst_len));
vs
(void)memcpy_s(dst, dst_len, src, src_len);
The question: how does an extra length parameter make code any more secure? To use memcpy(), I should already have all four parameters known and pass appropriate length as a third argument. What’s stopping me from making the same mistake of miscalculating destination buffer size and passing the wrong valus of dst_size? I can’t see why it’s any different from memcpy() and why it’s being deprecated. Is there any common use case that I can’t see? What am I missing here?
Nothing stops you from getting the parameters wrong in the “secure” version either. Microsoft seems to think that you’ll always use something like:
and check the error.
But this only helps people who don’t know what they’re doing with the language. In my opinion, that group of people either shouldn’t be using the language or they should learn how it works properly.
This sort of crutch doesn’t do them any favors in the long run since their code won’t be portable.
Now it may be that Microsoft did some analysis and found that there were a lot of problems caused by people misusing
memcpy()and they thought this would fix it. But, if that were the case, I suspect a better solution would be to educate the developers rather than forcing them to use non-standard features which will be unavailable in standard compilers.