strncpy_s, _strncpy_s_l, wcsncpy_s, _wcsncpy_s_l, _mbsncpy_s, _mbsncpy_s_l

文字列の文字を他の文字列にコピーします。 これらのバージョンの , , , , _wcsncpy_l_mbsncpy_l_mbsncpy には、CRT のセキュリティ機能に関する説明に従って、セキュリティが強化されています。 wcsncpy_strncpy_lstrncpy

重要

_mbsncpy_s および _mbsncpy_s_l は、Windows ランタイムで実行するアプリケーションでは使用できません。 詳細については、「ユニバーサル 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
使用するロケール。

戻り値

正常終了した場合はゼロ、切り捨てが行われた場合は STRUNCATE、それ以外の場合はエラー コード。

エラー条件

strDest numberOfElements strSource 戻り値 strDest の内容
NULL any any EINVAL 変更されない
any any NULL EINVAL 0 に設定された strDest[0]
any 0 any EINVAL 変更されない
NULL 以外 小さすぎる any ERANGE 0 に設定された strDest[0]

解説

これらの関数は、D の最初の strSource 文字を strDest にコピーしようとします。このとき、Dcount より小さく、strSource と同じ長さです。 これらのD文字が (サイズnumberOfElementsが指定されている) 内にstrDest収まり、null ターミネータの空き領域が残っている場合は、それらの文字がコピーされ、終端の null が追加されます。それ以外の場合は、null 文字に設定され、「strDest[0]パラメーターの検証」で説明されているように無効なパラメーター ハンドラーが呼び出されます。

上記の段落には例外があります。 ある場合count_TRUNCATE、常にstrDest追加される終端の strSource null の領域を残しながら、収まるのと同じ量がコピーされます。

たとえば、 にします。

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

は、5 文字を 5 バイトのバッファーにコピーすることを strncpy_s 意味します。 このコピーでは null ターミネータの領域が残されないため、 strncpy_s 文字列がゼロになり、無効なパラメーター ハンドラーが呼び出されます。

切り捨て動作が必要な場合は、次のように、_TRUNCATE を使用するか、size を 1 減算します。

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

と異なりstrncpy、長さがstrSource長さより大きい場合count、宛先文字列は長さまでの countnull 文字で埋め込まれません。

コピー元とコピー先の文字列が重なり合っている場合の strncpy_s 関数の動作は未定義です。

strDest または strSourceNULL である場合、または numberOfElements が 0 の場合、無効なパラメーター ハンドラーが呼び出されます。 実行の継続が許可された場合、関数は EINVAL を返し、errnoEINVAL に設定します。

wcsncpy_s 関数と _mbsncpy_s 関数は、strncpy_s 関数のワイド文字バージョンとマルチバイト文字バージョンです。 wcsncpy_smbsncpy_s は、これに応じて引数と戻り値が異なります。 それ以外では、これらの関数の動作は同じです。

出力値は、ロケールの 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

Note

_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>

互換性の詳細については、「 Compatibility」を参照してください。

例: char をバッファーにコピーする

// 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: ''

例: strncpy および strncpy_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'

関連項目

文字列操作
ロケール
マルチバイト文字シーケンスの解釈
_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