I maintain a fairly large piece of legacy code that still uses strncpy
a lot. I have now started the process of replacing the usage of strncpy
with
The definition of strncpy_s
is that elements beyond the null terminator take unspecified values. The definition of strncpy
is that those elements are set to 0
. If you don't want this behaviour, don't use strncpy_s
.
Also, strncpy_s
has different behaviour to strncpy
in the case that the input is too big for the buffer.
There are few valid use cases for strncpy
or strncpy_s
. It's almost always better to either use strcpy
, snprintf
, or memcpy
. My preference would strongly be to use whichever of those three functions is best suited to the task.
Calling it a "safe counterpart" is rather an exaggeration, IMO. The "non-safe" versions are actually all perfectly safe if you pass the correct arguments to them; and if you do not pass correct arguments then neither variety is safe.
If your code that uses strncpy
is actually not bugged, and you rely on the zero-padding feature, then there is no reason to change it.
strcpy_s()
will fill in the buffer with 'FE'
in debug mode only.
You can turn this off explicitly by calling _CrtSetDebugFillThreshold(0)