Перейти к содержимому

Strcpy си как работает

  • автор:

Strcpy си как работает

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

ОПИСАНИЕ

Функция strncpy() сходна, за исключением того, что скопировано будет только первые n байт из src. Внимание: если в первых n байт из src не окажется нулевого байта, то строка в dest также не будет завершена нулевым байтом.

Если длина src меньше n, strncpy() дописывает в dest нулевые байты, чтобы убедиться, что всего было записано n байт.

Простейшей реализацией strncpy() может быть:

ВОЗВРАЩАЕМОЕ ЗНАЧЕНИЕ

АТРИБУТЫ

Описание терминов данного раздела смотрите в attributes(7).

Интерфейс Атрибут Значение
strcpy(), strncpy() безвредность в нитях безвредно (MT-Safe)

СООТВЕТСТВИЕ СТАНДАРТАМ

ЗАМЕЧАНИЯ

Единственным правильным (и предполагаемым) использованием strncpy() является копирование C-строки в буфер фиксированной длины с одновременной проверкой того, что буфер не переполнен и неиспользованные байты в целевом буфере обнулены (для исключения возможной утечки информации в случае, если буфер будет записан на носитель или передан другому процессу через межпроцессовое общение).

Если в первых n байт src не будет завершающего нулевого байта, strncpy() создаст ничем не ограниченную строку в dest. Если размер buf равен buflen, вы можете принудительно завершить строку с помощью следующего кода:

Конечно же, вышеприведенный пример не учитывает того, что если размер src больше buflen — 1 байт, при копировании в dest будет потеряна часть информации.

strlcpy()

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

Эта функция подобна strncpy(), но копирует не более size-1 байт в dest, всегда добавляет конечный байт null и не дополняет назначение (помимо этого) байтами null. В данной функции исправлены некоторые проблемы strcpy() и strncpy(), но вызывающий по-прежнему должен обрабатывать возможность потери данных, если значение size окажется слишком мало. Возвращаемое значение функции — длина src, что позволяет легко обнаружить усечение: если возвращаемое значение больше или равно size, то выполнялось усечение. Если потеря данных неприемлема, то вызывающий должен или проверять аргументы перед вызовом, или проверять возвращаемое значение. Функция strlcpy() отсутствует в glibc и не стандартизована в POSIX, но доступна в Linux из библиотеки libbsd.

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 in C

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.

C strcpy()

In this tutorial, you will learn to use the strcpy() function in C programming to copy strings (with the help of an example).

C strcpy()

The function prototype of strcpy() is:

  • The strcpy() function copies the string pointed by source (including the null character) to the destination.
  • The strcpy() function also returns the copied string.

The strcpy() function is defined in the string.h header file.

Example: C strcpy()

Output

Note: When you use strcpy() , the size of the destination string should be large enough to store the copied string. Otherwise, it may result in undefined behavior.

Добавить комментарий

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