How to achieve strncpy() functionality with strncpy_s() function?
在某些情况下,我确实需要
1 | HRESULT someFunction( char* buffer, size_t length ); |
据记录,我可以在其中复制长度不超过
当然我会使用
1 2 3 4 5 6 7 8 9 10 | HRESULT someFunction( char* buffer, size_t length ) { const char* toCopy = ... size_t actualLength = strlen( toCopy ); if( actualLength > length ) { return E_UNEXPECTED; // doesn't fit, can't do anything reasonable } strncpy( buffer, toCopy, length ); return S_OK; } |
现在,我有了这段代码,需要将其从Visual C ++ 7迁移到Visual C ++9。我对其进行编译,并看到一条警告,提示
到目前为止,我应用的解决方案是只定义一个
有什么方法可以使用
您在这里面临的问题是您的函数本身不安全,就像
1 2 3 4 5 | // 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 ) |
这样,仅在绝对必须使用不安全功能的情况下,才能禁用这些警告。
您可以改用memcpy_s。
1 2 3 4 5 6 7 8 9 10 11 12 13 | HRESULT someFunction( char* buffer, size_t length ) { const char* toCopy = ... size_t actualLength = strlen( toCopy ); if( actualLength > length ) { return E_UNEXPECTED; // doesn't fit, can't do anything reasonable } else if ( actualLength < length ) { actualLength++; // copy null terminator too } memcpy_s( buffer, length, toCopy, actualLength ); return S_OK; } |
对于具有固定目标缓冲区的方案,尝试使用
1 2 3 4 | size_t actualLength = strlen( toCopy ); if( actualLength > length ) { return E_UNEXPECTED; // doesn't fit, can't do anything reasonable } |
因此代码在进行复制之前就知道了实际的字符串长度。一旦知道了长度,就可以使用
1 2 3 4 5 6 7 8 9 10 | HRESULT someFunction( char* buffer, size_t length ) { const char* toCopy = ... size_t actualLength = strlen( toCopy ); if( actualLength > length ) { return E_UNEXPECTED; // doesn't fit, can't do anything reasonable } memcpy( buffer, toCopy, min( length, actualLength + 1 ) ); return S_OK; } |
因此,解决方案是只忘记
您想在
因此,对于