How to achieve strncpy() functionality with strncpy_s() function?

后端 未结 4 939
小蘑菇
小蘑菇 2021-01-05 08:32

There\'re certain cases when I really need strncpy() funcitonalty - for example I have a function in a predefined interface that is passed an address of the buf

4条回答
  •  有刺的猬
    2021-01-05 09:05

    The problem you're facing here is that your function is unsafe in itself, just like strncpy() is. It is unsafe because callers of your function might forget that the returned strings are not null terminated. If this really is the desired behavior of your function I recommend not to define _CRT_SECURE_NO_WARNINGS and disable the warnings globally but use #pragmas instead:

    // document here exactly why you can not use strncpy_s
    #pragma warning( push )
    #pragma warning( disable : 4996 )
    // your code that uses strncpy instead of strncpy_s
    #pragma warning( pop ) 
    

    That way you disable those warnings only for those situations where you absolutely have to use unsafe functions.

提交回复
热议问题