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

后端 未结 4 948
小蘑菇
小蘑菇 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:14

    Trying to use str*cpy*() functions for scenarios with a fixed destination buffer is a common misconception. The deal here is that those functions "copy until a null character or other condition occurs". In this scenario there's this code in place:

    size_t actualLength = strlen( toCopy );
    if( actualLength > length ) {
        return E_UNEXPECTED; // doesn't fit, can't do anything reasonable 
    }
    

    and so the code knows the actual string length before it proceeds to copying. And once length is known it only makes sense to use memcpy() which is straightforward and concise for such scenarios and as a side effect also faster since it is allowed to copy more than one character at a time and doesn't check each character for null terminator.

    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;
    }
    

    So the solution is to just forget both strncpy() and strncpy_s() and use memcpy() instead.

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题