strncpy_s, _strncpy_s_l, wcsncpy_s, _wcsncpy_s_l, _mbsncpy_s, _mbsncpy_s_l

한 문자열의 문자를 다른 문자열에 복사합니다. CRT_strncpy_lstrncpy보안 기능에 설명된 대로 이러한 버전의 < _mbsncpy_lwcsncpy_wcsncpy_l_mbsncpy a0/>에는 보안 기능이 향상되었습니다.

Important

Windows 런타임에서 실행되는 애플리케이션에서는 _mbsncpy_s_mbsncpy_s_l을 사용할 수는 없습니다. 자세한 내용은 유니버설 Windows 플랫폼 앱에서 지원되지 않는 CRT 함수를 참조하세요.

구문

errno_t strncpy_s(
   char *strDest,
   size_t numberOfElements,
   const char *strSource,
   size_t count
);
errno_t _strncpy_s_l(
   char *strDest,
   size_t numberOfElements,
   const char *strSource,
   size_t count,
   _locale_t locale
);
errno_t wcsncpy_s(
   wchar_t *strDest,
   size_t numberOfElements,
   const wchar_t *strSource,
   size_t count
);
errno_t _wcsncpy_s_l(
   wchar_t *strDest,
   size_t numberOfElements,
   const wchar_t *strSource,
   size_t count,
   _locale_t locale
);
errno_t _mbsncpy_s(
   unsigned char *strDest,
   size_t numberOfElements,
   const unsigned char *strSource,
   size_t count
);
errno_t _mbsncpy_s_l(
   unsigned char *strDest,
   size_t numberOfElements,
   const unsigned char *strSource,
   size_t count,
   _locale_t locale
);
template <size_t size>
errno_t strncpy_s(
   char (&strDest)[size],
   const char *strSource,
   size_t count
); // C++ only
template <size_t size>
errno_t _strncpy_s_l(
   char (&strDest)[size],
   const char *strSource,
   size_t count,
   _locale_t locale
); // C++ only
template <size_t size>
errno_t wcsncpy_s(
   wchar_t (&strDest)[size],
   const wchar_t *strSource,
   size_t count
); // C++ only
template <size_t size>
errno_t _wcsncpy_s_l(
   wchar_t (&strDest)[size],
   const wchar_t *strSource,
   size_t count,
   _locale_t locale
); // C++ only
template <size_t size>
errno_t _mbsncpy_s(
   unsigned char (&strDest)[size],
   const unsigned char *strSource,
   size_t count
); // C++ only
template <size_t size>
errno_t _mbsncpy_s_l(
   unsigned char (&strDest)[size],
   const unsigned char *strSource,
   size_t count,
   _locale_t locale
); // C++ only

매개 변수

strDest
대상 문자열입니다.

numberOfElements
대상 문자열의 크기(문자)입니다.

strSource
소스 문자열입니다.

count
복사할 문자 수 또는 _TRUNCATE.

locale
사용할 로캘입니다.

반환 값

정상적으로 실행되는 경우 0이고 자르기가 수행되는 경우 STRUNCATE이며 그 외의 경우에는 오류 코드입니다.

오류 조건

strDest numberOfElements strSource 반환 값 strDest의 내용
NULL any any EINVAL 수정 안 됨
any any NULL EINVAL strDest[0]을 0으로 설정
any 0 any EINVAL 수정 안 됨
NULL 아님 너무 작음 any ERANGE strDest[0]을 0으로 설정

설명

이러한 함수는 strSource의 처음 D자를 strDest에 복사하려고 합니다. 여기서 DcountstrSource의 길이 중 더 작은 값입니다. 해당 D 문자가 (크기가 지정된numberOfElements) 내에 strDest 들어가고 null 종결자에 대한 공간을 유지하면 해당 문자가 복사되고 종료 null이 추가됩니다. 그렇지 않으면 strDest[0] null 문자로 설정되고 매개 변수 유효성 검사에 설명된 대로 잘못된 매개 변수 처리기가 호출됩니다.

위의 단락에는 예외가 있습니다. 이 _TRUNCATEstrSource 경우 count 항상 추가되는 종료 null에 대한 공간을 그대로 두고 있는 동안에 적합한 strDest 만큼 복사됩니다.

예를 들면 다음과 같습니다.

char dst[5];
strncpy_s(dst, 5, "a long string", 5);

는 5개 문자를 5 바이트 버퍼로 복사한다는 strncpy_s 의미입니다. 이 복사본은 null 종결자에 대한 공간을 남기지 않으므로 strncpy_s 문자열을 0으로 만들고 잘못된 매개 변수 처리기를 호출합니다.

잘림 동작이 필요한 경우 사용 _TRUNCATE 하거나 (size - 1):

strncpy_s(dst, 5, "a long string", _TRUNCATE);
strncpy_s(dst, 5, "a long string", 4);

의 길이strSource보다 큰 경우 count 와 달리 strncpy대상 문자열은 길이까지 countnull 문자로 채워지지 않습니다.

소스 문자열과 대상 문자열이 겹치는 경우 strncpy_s의 동작이 정의되지 않습니다.

strDest 또는 strSourceNULL이거나 numberOfElements가 0이면 잘못된 매개 변수 처리기가 호출됩니다. 계속해서 실행하도록 허용된 경우 함수가 EINVAL를 반환하며 errnoEINVAL로 설정합니다.

wcsncpy_s_mbsncpy_sstrncpy_s의 와이드 문자 및 멀티바이트 문자 버전입니다. 인수 및 반환 값은 wcsncpy_smbsncpy_s 그에 따라 다릅니다. 그 외의 경우에는 이들 6개 함수가 동일하게 작동합니다.

출력 값은 로캘의 LC_CTYPE 범주 설정 설정의 영향을 받습니다. 자세한 내용은 setlocale를 참조하세요. _l 접미사가 없는 이러한 함수 버전은 이 로캘 종속 동작에 현재 로캘을 사용하며, _l 접미사가 있는 버전은 전달된 로캘 매개 변수를 대신 사용하는 경우를 제외하고는 동일합니다. 자세한 내용은 Locale을 참조하세요.

C++에서는 템플릿 오버로드로 인해 이러한 함수를 사용하는 것이 보다 간단해 집니다. 오버로드는 버퍼 길이를 자동으로 유추할 수 있으며(크기 인수를 지정할 필요가 없어짐), 기존의 비보안 함수를 보다 최신의 보안 대응 함수로 자동으로 바꿀 수 있습니다. 자세한 내용은 보안 템플릿 오버로드를 참조 하세요.

이러한 함수의 디버그 라이브러리 버전은 먼저 버퍼를 0xFE 채웁니다. 이 동작을 사용하지 않도록 설정하려면 .를 사용합니다 _CrtSetDebugFillThreshold.

기본적으로 이 함수의 전역 상태는 애플리케이션으로 범위가 지정됩니다. 이 동작을 변경하려면 CRT의 전역 상태를 참조하세요.

일반 텍스트 루틴 매핑

TCHAR.H 루틴 _UNICODE 정의 _MBCS 되지 않음 _MBCS 정의 _UNICODE 정의
_tcsncpy_s strncpy_s _mbsnbcpy_s wcsncpy_s
_tcsncpy_s_l _strncpy_s_l _mbsnbcpy_s_l _wcsncpy_s_l

참고 항목

_strncpy_s_l_mbsncpy_s_l_wcsncpy_s_l 캘 의존성이 없습니다. 그들은 단지에 대해 _tcsncpy_s_l 제공되며 직접 호출 할 수 없습니다.

요구 사항

루틴에서 반환된 값 필수 헤더
strncpy_s, _strncpy_s_l <string.h>
wcsncpy_s, _wcsncpy_s_l <string.h> 또는 <wchar.h>
_mbsncpy_s, _mbsncpy_s_l <mbstring.h>

호환성에 대한 자세한 내용은 호환성을 참조하세요.

예: 버퍼에 문자 복사

// crt_strncpy_s_1.cpp
// compile with: /MTd

// these #defines enable secure template overloads
// (see last part of Examples() below)
#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1
#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES_COUNT 1

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <crtdbg.h>  // For _CrtSetReportMode
#include <errno.h>

// This example uses a 10-byte destination buffer.

errno_t strncpy_s_tester( const char * src,
                          int count )
{
   char dest[10];

   printf( "\n" );

   if ( count == _TRUNCATE )
      printf( "Copying '%s' to %d-byte buffer dest with truncation semantics\n",
               src, _countof(dest) );
   else
      printf( "Copying %d chars of '%s' to %d-byte buffer dest\n",
              count, src, _countof(dest) );

   errno_t err = strncpy_s( dest, _countof(dest), src, count );

   printf( "    new contents of dest: '%s'\n", dest );

   return err;
}

void Examples()
{
   strncpy_s_tester( "howdy", 4 );
   strncpy_s_tester( "howdy", 5 );
   strncpy_s_tester( "howdy", 6 );

   printf( "\nDestination buffer too small:\n" );
   strncpy_s_tester( "Hi there!!", 10 );

   printf( "\nTruncation examples:\n" );

   errno_t err = strncpy_s_tester( "How do you do?", _TRUNCATE );
   printf( "    truncation %s occur\n", err == STRUNCATE ? "did"
                                                       : "did not" );

   err = strncpy_s_tester( "Howdy.", _TRUNCATE );
   printf( "    truncation %s occur\n", err == STRUNCATE ? "did"
                                                       : "did not" );

   printf( "\nSecure template overload example:\n" );

   char dest[10];
   strncpy( dest, "very very very long", 15 );
   // With secure template overloads enabled (see #defines at
   // top of file), the preceding line is replaced by
   //    strncpy_s( dest, _countof(dest), "very very very long", 15 );
   // Instead of causing a buffer overrun, strncpy_s invokes
   // the invalid parameter handler.
   // If secure template overloads were disabled, strncpy would
   // copy 15 characters and overrun the dest buffer.
   printf( "    new contents of dest: '%s'\n", dest );
}

void myInvalidParameterHandler(
   const wchar_t* expression,
   const wchar_t* function,
   const wchar_t* file,
   unsigned int line,
   uintptr_t pReserved)
{
   wprintf(L"Invalid parameter handler invoked: %s\n", expression);
}

int main( void )
{
   _invalid_parameter_handler oldHandler, newHandler;

   newHandler = myInvalidParameterHandler;
   oldHandler = _set_invalid_parameter_handler(newHandler);
   // Disable the message box for assertions.
   _CrtSetReportMode(_CRT_ASSERT, 0);

   Examples();
}
Copying 4 chars of 'howdy' to 10-byte buffer dest
    new contents of dest: 'howd'

Copying 5 chars of 'howdy' to 10-byte buffer dest
    new contents of dest: 'howdy'

Copying 6 chars of 'howdy' to 10-byte buffer dest
    new contents of dest: 'howdy'

Destination buffer too small:

Copying 10 chars of 'Hi there!!' to 10-byte buffer dest
Invalid parameter handler invoked: (L"Buffer is too small" && 0)
    new contents of dest: ''

Truncation examples:

Copying 'How do you do?' to 10-byte buffer dest with truncation semantics
    new contents of dest: 'How do yo'
    truncation did occur

Copying 'Howdy.' to 10-byte buffer dest with truncation semantics
    new contents of dest: 'Howdy.'
    truncation did not occur

Secure template overload example:
Invalid parameter handler invoked: (L"Buffer is too small" && 0)
    new contents of dest: ''

예: strncpystrncpy_s

// crt_strncpy_s_2.c
// contrasts strncpy and strncpy_s

#include <stdio.h>
#include <stdlib.h>

int main( void )
{
   char a[20] = "test";
   char s[20];

   // simple strncpy usage:

   strcpy_s( s, 20, "dogs like cats" );
   printf( "Original string:\n   '%s'\n", s );

   // Here we can't use strncpy_s since we don't
   // want null termination
   strncpy( s, "mice", 4 );
   printf( "After strncpy (no null-termination):\n   '%s'\n", s );
   strncpy( s+5, "love", 4 );
   printf( "After strncpy into middle of string:\n   '%s'\n", s );

   // If we use strncpy_s, the string is terminated
   strncpy_s( s, _countof(s), "mice", 4 );
   printf( "After strncpy_s (with null-termination):\n   '%s'\n", s );

}
Original string:
   'dogs like cats'
After strncpy (no null-termination):
   'mice like cats'
After strncpy into middle of string:
   'mice love cats'
After strncpy_s (with null-termination):
   'mice'

참고 항목

문자열 조작
Locale
멀티바이트 문자 시퀀스 해석
_mbsnbcpy, _mbsnbcpy_l
strcat_s, wcscat_s, _mbscat_s
strcmp, wcscmp, _mbscmp
strcpy_s, wcscpy_s, _mbscpy_s
strncat_s, _strncat_s_l, wcsncat_s, _wcsncat_s_l, _mbsncat_s, _mbsncat_s_l
strncmp, wcsncmp, _mbsncmp, _mbsncmp_l
_strnicmp, _wcsnicmp, _mbsnicmp, _strnicmp_l, _wcsnicmp_l, _mbsnicmp_l
strrchr, wcsrchr, _mbsrchr, _mbsrchr_l
_strset, _strset_l, _wcsset, _wcsset_l, _mbsset, _mbsset_l
strspn, wcsspn, _mbsspn, _mbsspn_l