I got to know about the function - strncpy_s(), which is called the secure version of string copy. More secure than the functions - strcpy() and strncpy().
strncpy_s() is described more at this link - https://en.cppreference.com/w/c/string/byte/strncpy
I was thinking of using this function - strncpy_s() in my codebase to handle all the possible scenarios wherein its older siblings generally fail to handle - like when srcString is lengthier than destString. Or if srcString is not NULL terminated.
So I was wondering should the usage of strncpy_s() be -
strncpy_s(destString, sizeof(destString), srcString, (sizeof(srcString)>sizeof(destString)?(sizeof(destString)-1):(sizeof(srcString)-1)));
- [1]
to handle all the possible scenarios gracefully - ie
- when the srcString is greater than destString, then truncate the srcString to the length destString.
- when the destString is greater than srcString, then copy the entire content of srcString to destString with NULL termination.
- when both srcString and destString are of same length, then copy the entire content of srcString to destString with NULL termination.
- when srcString is not NULL terminated. If the srcString is smaller than destString then copy the one shy of the content of srcString to the destString with NULL termination. If destString is smaller than the srcString then copy the content from srcString of the size of destString.
Can anyone think that the above mentioned usage of strncpy_s() [1] could fail in any scenario, which I am not able to think of?
Edit: I have updated the action taken in the scenario - (2), (3) and (4)