What is the difference between wcsncpy and wcscpy_s?
Is there any practical difference between use wcscpy_s
and use wcsncpy
? The only difference seems to be the order of the parameters and the return value:
errno_t wcscpy_s(wchar_t *strDestination,
size_t numberOfElements,
const wchar_t *strSource);
wchar_t *wcsncpy(wchar_t *strDest,
const wchar_t *strSource,
size_t count );
And if there is no practical difference, why should Microsoft add wcscpy_s
to Visual Studio when a wcsncpy
standard feature was already available?
Can I replace wcscpy_s
with wcsncpy
when migrating from Visual Studio to gcc?
source to share
These two functions do not have the same behavior.
From MSDN documentationwcscpy_s
:
Upon successful execution, the destination string will always be null terminated.
From the spec wcsncpy
(C11 7.29.4.2.2 / 1-3):
#include <wchar.h> wchar_t *wcsncpy(wchar_t * restrict s1, const wchar_t * restrict s2, size_t n);
The function
wcsncpy
copies at mostn
wide characters (those that follow the null character; wide character is not copied) from the array it pointss2
to to the array it points tos1
.If the array pointed
s2
to is a wide string that is shorter thann
wide characters,s1
blank wide characters are appended to the copy in the array pointed to, beforen
wide characters were written in all
and footnote (# 346):
Thus, if there is no null wide character in the first
n
wide characters of the array pointed tos2
, the result will not be null-terminated.
Note that strncpy
and are wcsncpy
not intended to be used with null characters. They are intended for use with fixed width null encoded strings.
source to share
Another difference (it just cost me a couple of hours to stare at the code wondering what's going on) is that the default wcscpy_s function will terminate the application if you are about to intercept the buffer.
I expected it to behave like one of the strncpy variants. This is not true!
You can change this behavior with the _set_invalid_parameter_handler function.
source to share
wcscpy_s
is more secure , it can catch your error and call an Invalid Parameter Handler Procedure . To handle such errors without crashing they have provided _set_invalid_parameter_handler
.
source to share