Strncpy

Содержание:

备注Remarks

Strcpy_s函数将src地址中的内容(包括终止 null 字符)复制到dest指定的位置。The strcpy_s function copies the contents in the address of src, including the terminating null character, to the location that’s specified by dest. 目标字符串必须足够大以保存源字符串及其结尾的 null 字符。The destination string must be large enough to hold the source string and its terminating null character. 如果源和目标字符串重叠,则strcpy_s的行为不确定。The behavior of strcpy_s is undefined if the source and destination strings overlap.

wcscpy_s是strcpy_s的宽字符版本, _mbscpy_s为多字节字符版本。wcscpy_s is the wide-character version of strcpy_s, and _mbscpy_s is the multibyte-character version. Wcscpy_s的参数是宽字符字符串;_mbscpy_s和 _mbscpy_s_l的是多字节字符字符串。The arguments of wcscpy_s are wide-character strings; those of _mbscpy_s and _mbscpy_s_l are multibyte-character strings. 否则这些函数具有相同行为。These functions behave identically otherwise. _mbscpy_s_l与 _mbscpy_s相同,只不过它使用传入的区域设置参数而不是当前区域设置。_mbscpy_s_l is identical to _mbscpy_s except that it uses the locale parameter passed in instead of the current locale. 有关详细信息,请参阅 Locale。For more information, see Locale.

如果dest或src为空指针,或者如果目标字符串的大小dest_size太小,则调用无效参数处理程序,如参数验证中所述。If dest or src is a null pointer, or if the destination string size dest_size is too small, the invalid parameter handler is invoked, as described in Parameter Validation. 如果允许执行继续,则当dest或src为 null 指针时,这些函数将返回EINVAL ,并将errno设置为EINVAL ; 当目标字符串过小时,它们将返回ERANGE并将errno设置为ERANGE 。If execution is allowed to continue, these functions return EINVAL and set errno to EINVAL when dest or src is a null pointer, and they return ERANGE and set errno to ERANGE when the destination string is too small.

成功执行时,目标字符串始终以 null 结尾。Upon successful execution, the destination string is always null-terminated.

在 C++ 中,模板重载简化了这些函数的使用;重载可以自动推断缓冲区长度,从而无需指定大小自变量;并且它们可以自动将较旧、不安全的函数替换为更新、更安全的函数。In C++, use of these functions is simplified by template overloads that can infer buffer length automatically so that you don’t have to specify a size argument, and they can automatically replace older, less-secure functions with their newer, more secure counterparts. 有关详细信息,请参阅安全模板重载。For more information, see Secure Template Overloads.

这些函数的调试库版本首先用0xFE 填充缓冲区。The debug library versions of these functions first fill the buffer with 0xFE. 若要禁用此行为,请使用 _CrtSetDebugFillThreshold。To disable this behavior, use _CrtSetDebugFillThreshold.

默认情况下,此函数的全局状态的作用域限定为应用程序。By default, this function’s global state is scoped to the application. 若要更改此项,请参阅CRT 中的全局状态。To change this, see Global state in the CRT.

一般文本例程映射Generic-Text Routine Mappings

TCHAR.H 例程TCHAR.H routine 未定义 _UNICODE 和 _MBCS_UNICODE & _MBCS not defined 已定义 _MBCS_MBCS defined 已定义 _UNICODE_UNICODE defined
_tcscpy_s_tcscpy_s strcpy_sstrcpy_s _mbscpy_s_mbscpy_s wcscpy_swcscpy_s

Example

The following example demonstrates the use of strncpy and how it can be misused to cause program bugs and security issues. The compiler generates a warning for each call to strncpy similar to crt_strncpy_x86.c(15) : warning C4996: ‘strncpy’: This function or variable may be unsafe. Consider using strncpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

Output

The layout of automatic variables and the level of error detection and code protection can vary with changed compiler settings. This example may have different results when built in other compilation environments or with other compiler options.

RemarksRemarks

Функция strncpy копирует символы начального числа Стрсаурце в стрдест и возвращает стрдест.The strncpy function copies the initial count characters of strSource to strDest and returns strDest. Если параметр Count меньше или равен длине стрсаурце, то символ NULL не добавляется автоматически в скопированную строку.If count is less than or equal to the length of strSource, a null character is not appended automatically to the copied string. Если Count больше, чем длина стрсаурце, строка назначения дополняется символами NULL вплоть до длины.If count is greater than the length of strSource, the destination string is padded with null characters up to length count. Поведение strncpy не определено, если исходная и Целевая строки перекрываются.The behavior of strncpy is undefined if the source and destination strings overlap.

Важно!

strncpy не проверяет наличие достаточного места в стрдест; Это делает ее потенциальной причиной переполнения буфера.strncpy does not check for sufficient space in strDest; this makes it a potential cause of buffer overruns. Аргумент Count ограничивает количество копируемых символов. Он не является ограничением размера стрдест.The count argument limits the number of characters copied; it is not a limit on the size of strDest. См. указанный ниже пример.See the following example. Дополнительные сведения см. в разделе Как избежать переполнения буфера.For more information, see Avoiding Buffer Overruns.

Если стрдест или стрсаурце является пустым указателем или значение Count меньше или равно нулю, вызывается обработчик недопустимых параметров, как описано в разделе Проверка параметров.If strDest or strSource is a NULL pointer, or if count is less than or equal to zero, the invalid parameter handler is invoked, as described in Parameter Validation. Если выполнение может быть продолжено, эти функции возвращают-1 и устанавливают для еинвалзначение.If execution is allowed to continue, these functions return -1 and set errno to EINVAL.

wcsncpy и _mbsncpy — это версии strncpyдля расширенных символов и многобайтовых символов.wcsncpy and _mbsncpy are wide-character and multibyte-character versions of strncpy. Аргументы и возвращаемые значения wcsncpy и _mbsncpy различаются соответственно.The arguments and return value of wcsncpy and _mbsncpy vary accordingly. В остальном эти шесть функций ведут себя идентично.These six functions behave identically otherwise.

Версии этих функций с суффиксом _l идентичны за исключением того, что они используют переданный языковой стандарт вместо текущего языкового стандарта для поведения, зависящего от языкового стандарта.The versions of these functions with the _l suffix are identical except that they use the locale passed in instead of the current locale for their locale-dependent behavior. Для получения дополнительной информации см. Locale.For more information, see Locale.

В C++ эти функции имеют шаблонные перегрузки, которые вызывают более новые и безопасные аналоги этих функций.In C++, these functions have template overloads that invoke the newer, secure counterparts of these functions. Дополнительные сведения см. в разделе Безопасные перегрузки шаблонов.For more information, see Secure Template Overloads.

По умолчанию глобальное состояние этой функции ограничивается приложением.By default, this function’s global state is scoped to the application. Чтобы изменить это, см. раздел глобальное состояние в CRT.To change this, see Global state in the CRT.

Универсальное текстовое сопоставление функцийGeneric-Text Routine Mappings

Подпрограмма TCHAR.HTCHAR.H routine _UNICODE и _MBCS не определены_UNICODE & _MBCS not defined _MBCS определено_MBCS defined _UNICODE определено_UNICODE defined
_tcsncpy_tcsncpy strncpystrncpy _mbsnbcpy_mbsnbcpy wcsncpywcsncpy
_tcsncpy_l_tcsncpy_l _strncpy_l_strncpy_l _mbsnbcpy_l_mbsnbcpy_l _wcsncpy_l_wcsncpy_l

Примечание

_strncpy_l и _wcsncpy_l не имеют зависимости от языковых стандартов; они предоставляются только для _tcsncpy_l и не предназначены для непосредственного вызова._strncpy_l and _wcsncpy_l have no locale dependence; they are provided just for _tcsncpy_l and are not intended to be called directly.

Notes

Some programmers consider strncpy() to be inefficient and error prone. If the programmer knows (i.e., includes code to test!) that the size of
dest is greater than the length of src, then strcpy() can be used.

One valid (and intended) use of strncpy() is to copy a C string to a fixed-length buffer while ensuring both that the buffer is not overflowed and
that unused bytes in the target buffer are zeroed out (perhaps to prevent information leaks if the buffer is to be written to media or transmitted to another
process via an interprocess communication technique).

If there is no terminating null byte in the first n bytes of src, strncpy() produces an unterminated string in dest. You can
force termination using something like the following:

strncpy(buf, str, n);
if (n > 0)
    buf= '\0';
(Of course, the above technique ignores the fact that information contained in src is lost in the copying to dest.)

Some systems (the BSDs, Solaris, and others) provide the following function:

size_t strlcpy(char *dest, const char *src, size_t size);

This function is similar to strncpy(), but it copies at most size-1 bytes to dest, always adds a terminating null byte, and does not
pad the target with (further) null bytes. This function fixes some of the problems of strcpy() and strncpy(), but the caller must still handle
the possibility of data loss if size is too small. The return value of the function is the length of src, which allows truncation to be easily
detected: if the return value is greater than or equal to size, truncation occurred. If loss of data matters, the caller must either check the
arguments before the call, or test the function return value. strlcpy() is not present in glibc and is not standardized by POSIX, but is available on
Linux via the libbsd library.

Remarks

The strncpy function copies the initial count characters of strSource to strDest and returns strDest. If count is less than or equal to the length of strSource, a null character is not appended automatically to the copied string. If count is greater than the length of strSource, the destination string is padded with null characters up to length count. The behavior of strncpy is undefined if the source and destination strings overlap.

Important

strncpy does not check for sufficient space in strDest; this makes it a potential cause of buffer overruns. The count argument limits the number of characters copied; it is not a limit on the size of strDest. See the following example. For more information, see Avoiding Buffer Overruns.

If strDest or strSource is a NULL pointer, or if count is less than or equal to zero, the invalid parameter handler is invoked, as described in Parameter Validation. If execution is allowed to continue, these functions return -1 and set errno to EINVAL.

wcsncpy and _mbsncpy are wide-character and multibyte-character versions of strncpy. The arguments and return value of wcsncpy and _mbsncpy vary accordingly. These six functions behave identically otherwise.

The versions of these functions with the _l suffix are identical except that they use the locale passed in instead of the current locale for their locale-dependent behavior. For more information, see Locale.

In C++, these functions have template overloads that invoke the newer, secure counterparts of these functions. For more information, see Secure Template Overloads.

By default, this function’s global state is scoped to the application. To change this, see Global state in the CRT.

Generic-Text Routine Mappings

TCHAR.H routine _UNICODE & _MBCS not defined _MBCS defined _UNICODE defined
_tcsncpy strncpy _mbsnbcpy wcsncpy
_tcsncpy_l _strncpy_l _mbsnbcpy_l _wcsncpy_l

Note

_strncpy_l and _wcsncpy_l have no locale dependence; they are provided just for _tcsncpy_l and are not intended to be called directly.

Description

The strcpy() function copies the string pointed to by src, including the terminating null byte (‘\0’), to the buffer pointed to by
dest. The strings may not overlap, and the destination string dest must be large enough to receive the copy. Beware of buffer overruns!
(See BUGS.)

The strncpy() function is similar, except that at most n bytes of src are copied. Warning: If there is no null byte among the
first n bytes of src, the string placed in dest will not be null-terminated.

If the length of src is less than n, strncpy() writes additional null bytes to dest to ensure that a total of n bytes are
written.

A simple implementation of strncpy() might be:

char *
strncpy(char *dest, const char *src, size_t n)
{
    size_t i;

   for (i = 0; i < n && src != '\0'; i++)
        dest = src;
    for ( ; i < n; i++)
        dest = '\0';

   return dest;
}

RemarksRemarks

Функция strncpy копирует символы начального числа Стрсаурце в стрдест и возвращает стрдест.The strncpy function copies the initial count characters of strSource to strDest and returns strDest. Если параметр Count меньше или равен длине стрсаурце, то символ NULL не добавляется автоматически в скопированную строку.If count is less than or equal to the length of strSource, a null character is not appended automatically to the copied string. Если Count больше, чем длина стрсаурце, строка назначения дополняется символами NULL вплоть до длины.If count is greater than the length of strSource, the destination string is padded with null characters up to length count. Поведение strncpy не определено, если исходная и Целевая строки перекрываются.The behavior of strncpy is undefined if the source and destination strings overlap.

Важно!

strncpy не проверяет наличие достаточного места в стрдест; Это делает ее потенциальной причиной переполнения буфера.strncpy does not check for sufficient space in strDest; this makes it a potential cause of buffer overruns. Аргумент Count ограничивает количество копируемых символов. Он не является ограничением размера стрдест.The count argument limits the number of characters copied; it is not a limit on the size of strDest. См. указанный ниже пример.See the following example. Дополнительные сведения см. в разделе Как избежать переполнения буфера.For more information, see Avoiding Buffer Overruns.

Если стрдест или стрсаурце является пустым указателем или значение Count меньше или равно нулю, вызывается обработчик недопустимых параметров, как описано в разделе Проверка параметров.If strDest or strSource is a NULL pointer, or if count is less than or equal to zero, the invalid parameter handler is invoked, as described in Parameter Validation. Если выполнение может быть продолжено, эти функции возвращают-1 и устанавливают для еинвалзначение.If execution is allowed to continue, these functions return -1 and set errno to EINVAL.

wcsncpy и _mbsncpy — это версии strncpyдля расширенных символов и многобайтовых символов.wcsncpy and _mbsncpy are wide-character and multibyte-character versions of strncpy. Аргументы и возвращаемые значения wcsncpy и _mbsncpy различаются соответственно.The arguments and return value of wcsncpy and _mbsncpy vary accordingly. В остальном эти шесть функций ведут себя идентично.These six functions behave identically otherwise.

Версии этих функций с суффиксом _l идентичны за исключением того, что они используют переданный языковой стандарт вместо текущего языкового стандарта для поведения, зависящего от языкового стандарта.The versions of these functions with the _l suffix are identical except that they use the locale passed in instead of the current locale for their locale-dependent behavior. Для получения дополнительной информации см. Locale.For more information, see Locale.

В C++ эти функции имеют шаблонные перегрузки, которые вызывают более новые и безопасные аналоги этих функций.In C++, these functions have template overloads that invoke the newer, secure counterparts of these functions. Дополнительные сведения см. в разделе Безопасные перегрузки шаблонов.For more information, see Secure Template Overloads.

По умолчанию глобальное состояние этой функции ограничивается приложением.By default, this function’s global state is scoped to the application. Чтобы изменить это, см. раздел глобальное состояние в CRT.To change this, see Global state in the CRT.

Универсальное текстовое сопоставление функцийGeneric-Text Routine Mappings

Подпрограмма TCHAR.HTCHAR.H routine _UNICODE и _MBCS не определены_UNICODE & _MBCS not defined _MBCS определено_MBCS defined _UNICODE определено_UNICODE defined
_tcsncpy_tcsncpy strncpystrncpy _mbsnbcpy_mbsnbcpy wcsncpywcsncpy
_tcsncpy_l_tcsncpy_l _strncpy_l_strncpy_l _mbsnbcpy_l_mbsnbcpy_l _wcsncpy_l_wcsncpy_l

Примечание

_strncpy_l и _wcsncpy_l не имеют зависимости от языковых стандартов; они предоставляются только для _tcsncpy_l и не предназначены для непосредственного вызова._strncpy_l and _wcsncpy_l have no locale dependence; they are provided just for _tcsncpy_l and are not intended to be called directly.

構文Syntax

パラメーターParameters

先dest追加先の文字列バッファーの場所。Location of the destination string buffer.

dest_sizedest_sizeナロー関数とマルチバイト関数の場合は、ターゲット文字列バッファーのサイズ (単位)、 ワイド関数の場合は単位です。Size of the destination string buffer in units for narrow and multi-byte functions, and units for wide functions. この値は、0より大きく、 RSIZE_MAX以上である必要があります。This value must be greater than zero and not greater than RSIZE_MAX. このサイズのアカウントで、文字列の後に続くが使用されていることを確認し ます。Ensure that this size accounts for the terminating following the string.

srcsrcnull で終わる元の文字列バッファー。Null-terminated source string buffer.

localelocale使用するロケール。Locale to use.

ПримерExample

В следующем примере демонстрируется использование strncpy и способа, которым он может быть недоступен, чтобы вызвать ошибки программы и проблемы безопасности.The following example demonstrates the use of strncpy and how it can be misused to cause program bugs and security issues. Компилятор создает предупреждение для каждого вызова strncpy аналогично crt_strncpy_x86. c (15): Предупреждение C4996: «strncpy»: Эта функция или переменная может быть ненадежной. Вместо этого рекомендуется использовать strncpy_s. Чтобы отключить функцию устаревания, используйте _CRT_SECURE_NO_WARNINGS. Дополнительные сведения см. в справке в Интернете.The compiler generates a warning for each call to strncpy similar to crt_strncpy_x86.c(15) : warning C4996: ‘strncpy’: This function or variable may be unsafe. Consider using strncpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

Выходные данныеOutput

Макет автоматических переменных и уровень обнаружения ошибок и защиты кода могут варьироваться в зависимости от изменения в параметрах компилятора.The layout of automatic variables and the level of error detection and code protection can vary with changed compiler settings. Данный пример может дать иные результаты, если построить его в другой среде компиляции или с другими параметрами компилятора.This example may have different results when built in other compilation environments or with other compiler options.

Description

The strcpy() function copies the string pointed to by src, including the terminating null byte (‘\0’), to the buffer pointed to by
dest. The strings may not overlap, and the destination string dest must be large enough to receive the copy. Beware of buffer overruns!
(See BUGS.)

The strncpy() function is similar, except that at most n bytes of src are copied. Warning: If there is no null byte among the
first n bytes of src, the string placed in dest will not be null-terminated.

If the length of src is less than n, strncpy() writes additional null bytes to dest to ensure that a total of n bytes are
written.

A simple implementation of strncpy() might be:

char *
strncpy(char *dest, const char *src, size_t n)
{
    size_t i;

   for (i = 0; i < n && src != '\0'; i++)
        dest = src;
    for ( ; i < n; i++)
        dest = '\0';

   return dest;
}
Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *