Strcat

From Wikipedia, the free encyclopedia

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

In computing, the C programming language offers a library function called strcat that allows one memory block to be appended to another memory block. Both memory blocks are required to be null-terminated. Since, in C, strings are not first-class datatypes, and are implemented as blocks of ASCII bytes in memory, strcat will effectively append one string to another given two pointers to blocks of allocated memory. The name strcat is an abbreviation of "string concatenate". strcat is found in the string.h header file.

For example:

char str1[100] = "Hello,";    /* 100: reserve extra space */
strcat(str1, " world!\n");
printf(str1);                 /* prints "Hello, world!" to stdout */

Here is a possible implementation of strcat:

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

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

    return dest;
  }

It can also be defined in terms of other string library functions:

char *
strcat(char *dest, const char *src)
{
    strcpy(dest + strlen(dest), src);
    return dest;
}

strcat can be dangerous because if the string to be appended 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 bounded variant strncat does the same thing as strcat but as it only appends a specified number of bytes, it is susceptible to two types of buffer overflows. The first can only happen when the specified number of bytes is too large to fit in the destination string. The second is when the destination string can only hold the exact number of bytes specified to copy. This will result in an off by one error, and is often exploitable by a skilled attacker. OpenBSD strlcat is regarded as a safer version of these variants.

[edit] External links