How can I prevent strncpy_s from padding destination buffer in debug build?

后端 未结 2 1702
萌比男神i
萌比男神i 2021-01-19 04:27

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

2条回答
  •  没有蜡笔的小新
    2021-01-19 05:05

    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.

提交回复
热议问题