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?

+3


source to share


4 answers


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 most n

wide characters (those that follow the null character; wide character is not copied) from the array it points s2

to to the array it points to s1

.

If the array pointed s2

to is a wide string that is shorter than n

wide characters, s1

blank wide characters are appended to the copy in the array pointed to, before n

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 to s2

, 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.

+9


source


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.

+3


source


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

.

+1


source


Functions with _s appended are whoch functions are more secure. Typically features unrelated to trailing _s will be marked "deprecated" by VS2012, for example. You will receive a warning. For more information: MSDN has a lot of information on this.

0


source







All Articles