How to implement strncpy () function using strncpy_s () function?

There are certain cases when I really need the strncpy()funcitonalty function - for example, I have a function in a predefined interface to which the buffer address and buffer size are passed:

HRESULT someFunction( char* buffer, size_t length );

and it’s documented that I can copy a null-terminated string with a length of no more length- if it is exactly equal to the length lengthI am not null-terminated, and the caller knows that the string ends with either a null character or a length length, whichever happens first and it all works.

Of course I will use strncpy()for this

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 ++ 7 Visual ++ 9. . , strncpy() , strncpy_s().

strncpy_s() , - , . E_UNEXPECTED , length - 1 ( length, ), , length , undefined.

, , - _CRT_SECURE_NO_WARNINGS .

strncpy_s() strncpy()?

+5
4

str*cpy*() . , " ". :

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

. , memcpy(), , .

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

, , strncpy(), strncpy_s() memcpy().

+2

, , , , strncpy(). , , . , _CRT_SECURE_NO_WARNINGS , #pragmas:

// 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 ) 

, .

+4

memcpy_s.

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

, actualLength < length, , actualLength == length, ?

strncpy_s , actualLength < length memcpy_s actualLength == length.

+1

All Articles