Про разницу между strlcat и strncat
Содержание:
Remarks
The strcat_s function appends strSource to strDestination and terminates the resulting string with a null character. The initial character of strSource overwrites the terminating null character of strDestination. The behavior of strcat_s is undefined if the source and destination strings overlap.
Note that the second parameter is the total size of the buffer, not the remaining size:
wcscat_s and _mbscat_s are wide-character and multibyte-character versions of strcat_s. The arguments and return value of wcscat_s are wide-character strings; those of _mbscat_s are multibyte-character strings. These three functions behave identically otherwise.
If strDestination is a null pointer, or is not null-terminated, or if strSource is a NULL pointer, or if the destination string is too small, the invalid parameter handler is invoked, as described in Parameter Validation. If execution is allowed to continue, these functions return EINVAL and set errno to EINVAL.
The versions of functions that have the _l suffix have the same behavior, but use the locale parameter that’s passed in instead of the current locale. For more information, see Locale.
In C++, using these functions is simplified by template overloads; the overloads can infer buffer length automatically (eliminating the need to specify a size argument) and they can automatically replace older, non-secure functions with their newer, secure counterparts. For more information, see Secure Template Overloads.
The debug library versions of these functions first fill the buffer with 0xFE. To disable this behavior, use _CrtSetDebugFillThreshold.
By default, this function’s global state is scoped to the application. To change this, see Global state in the CRT.
Возвращаемое значениеReturn Value
Возвращает 0 в случае успеха или код ошибки в случае неудачи.Returns 0 if successful, an error code on failure.
Ситуации, которые могут привести к ошибкеError Conditions
| стрдестинатионstrDestination | numberOfElementsnumberOfElements | стрсаурцеstrSource | Возвращаемое значениеReturn value | Содержимое стрдестинатионContents of strDestination |
|---|---|---|---|---|
| Null или без завершенияNULL or unterminated | anyany | anyany | еинвалEINVAL | не измененоnot modified |
| anyany | anyany | ЗАКАНЧИВАЮЩNULL | еинвалEINVAL | не измененоnot modified |
| anyany | 0 или слишком мал0, or too small | anyany | ERANGEERANGE | не измененоnot modified |
СинтаксисSyntax
ПараметрыParameters
destdestРасположение строкового буфера назначения.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. Это значение должно быть больше нуля и не больше 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.
srcsrcИсходная строка, завершающаяся нулем.Null-terminated source string buffer.
localelocaleИспользуемый языковой стандарт.Locale to use.
RemarksRemarks
Функция strcat_s добавляет стрсаурце к стрдестинатион и завершает результирующую строку символом NULL.The strcat_s function appends strSource to strDestination and terminates the resulting string with a null character. Начальный символ стрсаурце перезаписывает завершающий нуль символ стрдестинатион.The initial character of strSource overwrites the terminating null character of strDestination. Поведение strcat_s не определено, если строки источника и назначения перекрываются.The behavior of strcat_s is undefined if the source and destination strings overlap.
Обратите внимание, что второй параметр — это общий размер буфера, а не оставшийся размер:Note that the second parameter is the total size of the buffer, not the remaining size:
wcscat_s и _mbscat_s — это версии strcat_sдля расширенных символов и многобайтовых символов.wcscat_s and _mbscat_s are wide-character and multibyte-character versions of strcat_s. Аргументы и возвращаемое значение wcscat_s являются строками расширенных символов; _mbscat_s являются строками многобайтовых символов.The arguments and return value of wcscat_s are wide-character strings; those of _mbscat_s are multibyte-character strings. В остальном эти три функции ведут себя идентично.These three functions behave identically otherwise.
Если стрдестинатион является пустым указателем или не завершается нулем или если стрсаурце является пустым указателем или если строка назначения слишком мала, вызывается обработчик недопустимых параметров, как описано в разделе Проверка параметров.If strDestination is a null pointer, or is not null-terminated, or if strSource is a NULL pointer, or if the destination string is too small, the invalid parameter handler is invoked, as described in Parameter Validation. Если выполнение может быть продолжено, эти функции возвращают еинвал и применяют значение » еинвал».If execution is allowed to continue, these functions return EINVAL and set errno to EINVAL.
Версии функций с суффиксом _l имеют одинаковое поведение, но используют переданный параметр языкового стандарта вместо текущего языкового стандарта.The versions of functions that have the _l suffix have the same behavior, but use the locale parameter that’s passed in instead of the current locale. Для получения дополнительной информации см. Locale.For more information, see Locale.
В C++ использование данных функций упрощено наличием шаблонных перегрузок; перегруженные методы могут автоматически определять длину буфера (что исключает необходимость указания аргумента с размером буфера), а также они могут автоматически заменять более старые, незащищенные функции их новыми безопасными аналогами.In C++, using these functions is simplified by template overloads; the overloads can infer buffer length automatically (eliminating the need to specify a size argument) and they can automatically replace older, non-secure functions with their newer, 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.HTCHAR.H routine | _UNICODE и _MBCS не определены_UNICODE & _MBCS not defined | _MBCS определено_MBCS defined | _UNICODE определено_UNICODE defined |
|---|---|---|---|
| _tcscat_s_tcscat_s | strcat_sstrcat_s | _mbscat_s_mbscat_s | wcscat_swcscat_s |
Возвращаемое значениеReturn Value
Ноль в случае успеха, стрункате , если произошло усечение, в противном случае — код ошибки.Zero if successful, STRUNCATE if truncation occurred, otherwise an error code.
Ситуации, которые могут привести к ошибкеError Conditions
| стрдестstrDest | numberOfElementsnumberOfElements | стрсаурцеstrSource | Возвращаемое значениеReturn value | Содержимое стрдестContents of strDest |
|---|---|---|---|---|
| ЗАКАНЧИВАЮЩNULL | anyany | anyany | еинвалEINVAL | не измененоnot modified |
| anyany | anyany | ЗАКАНЧИВАЮЩNULL | еинвалEINVAL | стрдест имеет значение 0strDest set to 0 |
| anyany | anyany | еинвалEINVAL | не измененоnot modified | |
| не nullnot NULL | слишком малоtoo small | anyany | ERANGEERANGE | стрдест имеет значение 0strDest set to 0 |
Remarks
The strncat function appends, at most, the first count characters of strSource to strDest. The initial character of strSource overwrites the terminating null character of strDest. If a null character appears in strSource before count characters are appended, strncat appends all characters from strSource, up to the null character. If count is greater than the length of strSource, the length of strSource is used in place of count. The all cases, the resulting string is terminated with a null character. If copying takes place between strings that overlap, the behavior is undefined.
Important
strncat does not check for sufficient space in strDest; it is therefore a potential cause of buffer overruns. Keep in mind that count limits the number of characters appended; it is not a limit on the size of strDest. See the example below. For more information, see Avoiding Buffer Overruns.
wcsncat and _mbsncat are wide-character and multibyte-character versions of strncat. The string arguments and return value of wcsncat are wide-character strings; those of _mbsncat are multibyte-character strings. These three functions behave identically otherwise.
The output value is affected by the setting of the LC_CTYPE category setting of the locale; see setlocale for more information. The versions of these functions without the _l suffix use the current locale for this locale-dependent behavior; the versions with the _l suffix are identical except that they use the locale parameter passed in instead. For more information, see Locale.
In C++, these functions have template overloads. 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 |
|---|---|---|---|
| _tcsncat | strncat | _mbsnbcat | wcsncat |
| _tcsncat_l | _strncat_l | _mbsnbcat_l | _wcsncat_l |
Note
_strncat_l and _wcsncat_l have no locale dependence and are not meant to be called directly. They are provided for internal use by _tcsncat_l.
ПримечанияRemarks
Функция strcat добавляет стрсаурце в стрдестинатион и завершает результирующую строку символом NULL.The strcat function appends strSource to strDestination and terminates the resulting string with a null character. Начальный символ стрсаурце перезаписывает завершающий нуль символ стрдестинатион.The initial character of strSource overwrites the terminating null character of strDestination. Поведение strcat не определено, если исходная и Целевая строки перекрываются.The behavior of strcat is undefined if the source and destination strings overlap.
Важно!
Так как strcat не проверяет наличие достаточного места в стрдестинатион перед добавлением стрсаурце, это может стать причиной переполнения буфера.Because strcat does not check for sufficient space in strDestination before appending strSource, it is a potential cause of buffer overruns. Рекомендуется использовать вместо нее функцию strncat.Consider using strncat instead.
wcscat и _mbscat — это версии strcatдля расширенных символов и многобайтовых символов.wcscat and _mbscat are wide-character and multibyte-character versions of strcat. Аргументы и возвращаемое значение wcscat являются строками расширенных символов. _mbscat являются строками многобайтовых символов.The arguments and return value of wcscat are wide-character strings; those of _mbscat are multibyte-character strings. В остальном эти три функции ведут себя идентично.These three functions behave identically otherwise.
В C++ эти функции имеют шаблонные перегрузки, которые вызывают более новые и безопасные аналоги этих функций.In C++, these functions have template overloads that invoke the newer, secure counterparts of these functions. Дополнительные сведения см. в разделе Secure Template Overloads.For more information, see Secure Template Overloads.
Сопоставления подпрограмм обработки обычного текстаGeneric-Text Routine Mappings
| Подпрограмма TCHAR.HTCHAR.H routine | _UNICODE и _MBCS не определены_UNICODE & _MBCS not defined | _MBCS определено_MBCS defined | _UNICODE определено_UNICODE defined |
|---|---|---|---|
| _tcscat_tcscat | strcatstrcat | _mbscat_mbscat | wcscatwcscat |
Remarks
These functions try to append the first D characters of strSource to the end of strDest, where D is the lesser of count and the length of strSource. If appending those D characters will fit within strDest (whose size is given as numberOfElements) and still leave room for a null terminator, then those characters are appended, starting at the original terminating null of strDest, and a new terminating null is appended; otherwise, strDest is set to the null character and the invalid parameter handler is invoked, as described in Parameter Validation.
There is an exception to the above paragraph. If count is _TRUNCATE then as much of strSource as will fit is appended to strDest while still leaving room to append a terminating null.
For example,
means that we are asking strncat_s to append three characters to two characters in a buffer five characters long; this would leave no space for the null terminator, hence strncat_s zeroes out the string and calls the invalid parameter handler.
If truncation behavior is needed, use _TRUNCATE or adjust the size parameter accordingly:
or
In all cases, the resulting string is terminated with a null character. If copying takes place between strings that overlap, the behavior is undefined.
If strSource or strDest is NULL, or is numberOfElements is zero, the invalid parameter handler is invoked, as described in Parameter Validation . If execution is allowed to continue, the function returns EINVAL without modifying its parameters.
wcsncat_s and _mbsncat_s are wide-character and multibyte-character versions of strncat_s. The string arguments and return value of wcsncat_s are wide-character strings; those of _mbsncat_s are multibyte-character strings. These three functions behave identically otherwise.
The output value is affected by the setting of the LC_CTYPE category setting of the locale; see setlocale for more information. The versions of these functions without the _l suffix use the current locale for this locale-dependent behavior; the versions with the _l suffix are identical except that they use the locale parameter passed in instead. For more information, see Locale.
In C++, using these functions is simplified by template overloads; the overloads can infer buffer length automatically (eliminating the need to specify a size argument) and they can automatically replace older, non-secure functions with their newer, secure counterparts. For more information, see Secure Template Overloads.
The debug library versions of these functions first fill the buffer with 0xFE. To disable this behavior, use _CrtSetDebugFillThreshold.
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 |
|---|---|---|---|
| _tcsncat_s | strncat_s | _mbsnbcat_s | wcsncat_s |
| _tcsncat_s_l | _strncat_s_l | _mbsnbcat_s_l | _wcsncat_s_l |
_strncat_s_l and _wcsncat_s_l have no locale dependence; they are only provided for _tcsncat_s_l.
Копирование
void * memcpy (void * destination, const void * source, size_t num);
Копирует участок памяти из source в destination, размером num байт. Функция очень полезная, с помощью неё, например, можно скопировать объект или перенести участок массива, вместо поэлементного копирования. Функция производит бинарное копирование, тип данных не важен. Например, удалим элемент из массива и сдвинем остаток массива влево.
#include <conio.h>
#include <stdio.h>
#include <string.h>
#define SIZE 10
int main() {
int a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
unsigned index;
int i;
printf("Enter index ");
scanf("%ud", &index);
index = index < SIZE? index: SIZE-1;
memcpy(&a, &a, sizeof(int) * (SIZE - index - 1));
for (i = 0; i < SIZE; i++) {
printf("%d ", a);
}
getch();
}
Функция меняет местами две переменные
#include <conio.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void swap(void* a, void* b, size_t size) {
void *tmp = malloc(size);
memcpy(tmp, a, size);
memcpy(a, b, size);
memcpy(b, tmp, size);
free(tmp);
}
int main() {
float a = 300.456;
float b = 0.645;
swap(&a, &b, sizeof(float));
printf("a = %.3f\nb = %.3f", a, b);
getch();
}
Здесь хотелось бы отметить, что функция выделяет память под временную переменную. Это дорогостоящая операция. Для улучшения производительности стоит передавать функции временную переменную, которая будет создана один раз.
#include <conio.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void swap(void* a, void* b, void* tmp, size_t size) {
memcpy(tmp, a, size);
memcpy(a, b, size);
memcpy(b, tmp, size);
}
int main() {
float a = 300.456;
float b = 0.645;
float tmp;
swap(&a, &b, &tmp, sizeof(float));
printf("a = %.3f\nb = %.3f", a, b);
getch();
}
void* memmove (void * destination, const void * source, size_t num);
Копирует блок памяти из source в destination размером num байт с той разницей, что области могут пересекаться. Во время копирования используется промежуточный буфер, который предотвращает перекрытие областей.
#include <stdio.h>
#include <string.h>
#include <conio.h>
void main () {
char str[] = "memmove can be very useful......";
memmove (str + 20, str + 15, 11);
puts(str);
getch();
}
Пример взят из cplusplus.com
char* strcpy (char * destination, const char* source );
Копирует одну строку в другую, вместе с нулевым символом. Также возвращает указатель на destination.
#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <stdlib.h>
void main () {
char buffer;
char *word = NULL;
scanf("%127s", buffer);
word = (char*) malloc(strlen(buffer)+1);
strcpy(word, buffer);
printf("%s", word);
free(word);
getch();
}
Можно копировать и по-другому
#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <stdlib.h>
void main () {
char buffer;
char *word = NULL;
char *other = NULL;
scanf("%127s", buffer);
word = (char*) malloc(strlen(buffer)+1);
other = strcpy(word, buffer);
printf("%s", other);
free(other);
getch();
}
char* strncpy (char* destination, const char* source, size_t num);
Копирует только num первых букв строки. 0 в конец не добавляется автоматически. При копировании из строки в эту же строку части не должны пересекаться (при пересечении используйте memmove)
#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <stdlib.h>
void main () {
char word[] = "Aloha, Hawaii";
char aloha;
char hawaii;
strncpy(aloha, word, 5);
aloha = 0;
strncpy(hawaii, &word, 7);
printf("%s, %s", aloha, hawaii);
getch();
}
RemarksRemarks
Функция strcpy копирует стрсаурце, включая завершающий символ null, в расположение, указанное в стрдестинатион.The strcpy function copies strSource, including the terminating null character, to the location that’s specified by strDestination. Поведение strcpy не определено, если исходная и Целевая строки перекрываются.The behavior of strcpy is undefined if the source and destination strings overlap.
Важно!
Так как strcpy не проверяет наличие достаточного места в стрдестинатион перед копированием стрсаурце, это может привести к переполнению буфера.Because strcpy does not check for sufficient space in strDestination before it copies strSource, it is a potential cause of buffer overruns. Рекомендуем использовать вместо этой функции функцию strcpy_s.Therefore, we recommend that you use strcpy_s instead.
wcscpy и _mbscpy — это версии strcpy, соответственно, расширенных символов и многобайтовых символов.wcscpy and _mbscpy are, respectively, wide-character and multibyte-character versions of strcpy. Аргументы и возвращаемое значение wcscpy являются строками расширенных символов. _mbscpy являются строками многобайтовых символов.The arguments and return value of wcscpy are wide-character strings; those of _mbscpy are multibyte-character strings. В остальном эти три функции ведут себя идентично.These three functions behave identically otherwise.
В 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 |
|---|---|---|---|
| _tcscpy_tcscpy | strcpystrcpy | _mbscpy_mbscpy | wcscpywcscpy |
DESCRIPTION top
The strcat() function appends the src string to the dest string,
overwriting the terminating null byte ('\0') at the end of dest, and
then adds a terminating null byte. The strings may not overlap, and
the dest string must have enough space for the result. If dest is
not large enough, program behavior is unpredictable; buffer overruns
are a favorite avenue for attacking secure programs.
The strncat() function is similar, except that
* it will use at most n bytes from src; and
* src does not need to be null-terminated if it contains n or more
bytes.
As with strcat(), the resulting string in dest is always null-
terminated.
If src contains n or more bytes, strncat() writes n+1 bytes to dest
(n from src plus the terminating null byte). Therefore, the size of
dest must be at least strlen(dest)+n+1.
A simple implementation of strncat() might be:
char *
strncat(char *dest, const char *src, size_t n)
{
size_t dest_len = strlen(dest);
size_t i;
for (i = 0 ; i < n && src != '\0' ; i++)
dest = src;
dest = '\0';
return dest;
}
NOTES top
Some systems (the BSDs, Solaris, and others) provide the following
function:
size_t strlcat(char *dest, const char *src, size_t size);
This function appends the null-terminated string src to the string
dest, copying at most size-strlen(dest)-1 from src, and adds a
terminating null byte to the result, unless size is less than
strlen(dest). This function fixes the buffer overrun problem of
strcat(), but the caller must still handle the possibility of data
loss if size is too small. The function returns the length of the
string strlcat() tried to create; if the return value is greater than
or equal to size, data loss occurred. If data loss matters, the
caller must either check the arguments before the call, or test the
function return value. strlcat() is not present in glibc and is not
standardized by POSIX, but is available on Linux via the libbsd
library.
EXAMPLES top
Because strcat() and strncat() must find the null byte that
terminates the string dest using a search that starts at the
beginning of the string, the execution time of these functions scales
according to the length of the string dest. This can be demonstrated
by running the program below. (If the goal is to concatenate many
strings to one target, then manually copying the bytes from each
source string while maintaining a pointer to the end of the target
string will provide better performance.)
Program source
#include <string.h>
#include <time.h>
#include <stdio.h>
int
main(int argc, char *argv[])
{
#define LIM 4000000
int j;
char p; /* +1 for terminating null byte */
time_t base;
base = time(NULL);
p = '\0';
for (j = 0; j < LIM; j++) {
if ((j % 10000) == 0)
printf("%d %ld\n", j, (long) (time(NULL) - base));
strcat(p, "a");
}
}