Strcpy си как работает
strDestination
Строка, являющаяся выходным значением.
strSource
Исходная строка с нулевым символом в конце.
Возвращаемое значение
Каждая из этих функций возвращает строку, являющуюся выходным значением. Возвращаемых значений, указывающих на ошибку, нет.
Замечания
Функция strcpy копирует строку,указанную параметром strSource, включая символ завершающего нуля, в место, указанное параметром strDestination. Поведение strcpy не определяется, если источниковая и являющаяся выходным значением строки накладываются друг на друга.
| Предупреждение по безопасности Поскольку функция strcpy не проверяет достаточно ли места в строковом массиве, указанном strDestination прежде, чем скопировать туда strSource, это — потенциальная причина переполнения буфера. Рассмотрите лучше использование функции strncpy вместо этой. |
Функции wcscpy и _mbscpy — широкосимвольные и многобайтово-символьные версии strcpy. Параметры и возвращаемое значение wcscpy — широкосимвольные строки; а _mbscpy являются многобайтово-символьными строками. В противном случае эти три функции ведут себя тождественно.
STRCPY
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:
RETURN VALUE
ATTRIBUTES
Multithreading (see pthreads(7))
CONFORMING TO
NOTES
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 . If buf has length buflen , you can force termination using something like the following:
(Of course, the above technique ignores the fact that, if src contains more than buflen — 1 bytes, information is lost in the copying to dest .)
strlcpy()
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.
Strcpy си как работает
strcpy is a C standard library function that copies a string from one location to another. It is defined in the string.h header file.
The function takes two arguments: a destination buffer where the copied string will be stored, and a source string that will be copied. The function copies the entire source string, including the null terminator, into the destination buffer.
The C strcpy() function copies the content of a string to another. The content of the destination string will be replaced with that of the source string by the strcpy() function. It is defined inside <string.h> header file.
Syntax:
Parameters: This method accepts the following parameters:
- destination: Pointer to the destination character array where the content is to be copied.
- source: Pointer to the source character array which is to be copied.
Return Value: A pointer to the destination string is returned after the strcpy() function copies the source string.
Example: 1
EXAMPLE 2 :
Important Points
- Using this function, you can copy the entire string to the destination string. Source strings are not appended to destination strings. As a result, the content of the destination string is replaced by the content of the source string.
- Source strings are not affected. After copying, the source string remains the same.
- To use strcpy(), the string.h header file must be included.
- In the case of a longer source string (Character Array), strcpy() performs undefined behavior.
ADVANTAGES AND DISADVANTAGES:
Some advantages of using strcpy in C include:
It is a simple and easy-to-use function that can be used to copy strings quickly and easily.
It is a standard library function, so it is widely available and portable across different platforms and compilers.
It is relatively fast, as it only requires a single pass through the source string to copy it.
However, there are also some disadvantages to consider when using strcpy:
It does not check the size of the destination buffer, so it is possible to overwrite the buffer and cause a buffer overflow if the source string is longer than the destination buffer. This can lead to security vulnerabilities and other problems.
It does not handle overlapping strings properly. If the source and destination strings overlap, the behavior of strcpy is undefined.
It does not handle null characters within the source string properly. If the source string contains a null character, strcpy will stop copying at that point, even if there are additional characters in the source string.
strcpy, strcpy_s
strcpy_s is allowed to clobber the destination array from the last character written up to destsz in order to improve efficiency: it may copy in multibyte blocks and then check for null bytes.
The function strcpy_s is similar to the BSD function strlcpy , except that
- strlcpy truncates the source string to fit in the destination (which is a security risk)
- strlcpy does not perform all the runtime checks that strcpy_s does
- strlcpy does not make failures obvious by setting the destination to a null string or calling a handler if the call fails.
Although strcpy_s prohibits truncation due to potential security risks, it’s possible to truncate a string using bounds-checked strncpy_s instead.