I'm not impressed by Microsoft's memcpy_s()
because it is still up to the caller to supply the destination buffer size. Since the main thing that can go wrong with memcpy()
(excepting if the source and destination buffers overlap) is caused by not knowing how big the destination buffer really is, is it not likely that the caller will put the wrong size for the destination in?
I suppose there is one class of errors it will help with exemplified by:
char anArray[10]
char* foo = anArray;
memcpy_s(foo, sizeof foo, somewhereElse, 10);
// or
memcpy_s(foo, sizeof *foo, somewhereElse, 10);
However, both of these demonstrate a fundamental misunderstanding of C pointers and will likely not be the only problems with the code.
And what do you do if the destination is too small? Do you carry on with the truncated data? Do you put out an error message saying "Alert: programmer is an idiot"? No, it's better to know that your destination buffer is big enough before starting to do the copy.
Also, the link in the question talks about memcpy_s()
having a null pointer check. Again, what are you going to do? Having the program crash is about all you can do sanely because, if a pointer you expected not to be null is null, you can't trust any part of your program's running environment. And on modern PC operating systems, the program will crash as soon as memcpy()
attempts to dereference the null pointer.