Strcpy

From Wikipedia, the free encyclopedia

The correct title of this article is strcpy. The initial letter is shown capitalized due to technical restrictions.

The C programming language offers a library function called strcpy, located in string.h, that allows null-terminated memory blocks to be copied from one location to another. Since strings in C are not first-class datatypes and are implemented instead as contiguous blocks of ASCII bytes in memory, strcpy will effectively copy strings given two pointers to blocks of allocated memory.

Contents

[edit] Usage and implementation

For example

char *str1 = malloc(LARGE_NUMBER);
char *str2 = malloc(LARGE_NUMBER);

fgets(str1, LARGE_NUMBER, stdin);
strcpy(str2, str1); /* the argument order mimics that of an assignment: str2 "=" str1 */

Although the simple assignment str2 = str1 might appear to do the same thing, it only copies the memory address of str1 into str2, so the variables now point at the same region of memory (thus any modification made to one string will affect the other). This is known as a shallow copy because it does not actually create a new, identical string.

The strcpy function performs a copy by iterating over the individual characters of the string and copying them one by one. The following is a short-hand implementation of strcpy

 char *strcpy (char *dest, const char *src) 
 {
     char *p = dest;
     while((*dest++ = *src++));
     return p;
 }

It is semantically equivalent to the more explicit:

 char *strcpy (char *dest, const char *src) 
 {
   const char *p;
   char *q; 

   for(p = src, q = dest; *p != '\0'; p++, q++)
      *q = *p;
   
   *q = '\0';

   return dest;
 }

[edit] Buffer overflows

strcpy can be dangerous because if the string to be copied is too long to fit in the destination buffer, it will overwrite adjacent memory, causing unpredictable behavior. Usually the program will simply cause a segmentation fault when this occurs, but a skilled attacker can use such a buffer overflow to crack into a system (see computer security).

[edit] Bounds checking variants

The most common bounded variant, strncpy, does the same thing as strcpy but as it only copies a specified number of bytes and then zeros out the destination buffer until it reaches the specified maximum length. It is susceptible to buffer overflow only if the number of bytes specified is larger than the destination string; however because it does not guarantee null termination of strings when the source string is longer than the specified maximum length it can sometimes result in a read exception if the program later assumes the output string is properly null terminated. OpenBSD's strlcpy is often regarded as a safer version of these variants; where this is not available, some libraries such as GLib provide a wrapper[1] that calls strncpy and then sets the final byte to null. The glibc developers, however, suggest using memcpy.[citation needed]

[edit] External links

In other languages