CS 3 (Spring 2024) strcat

Name

strcat - concatenate two strings

Synopsis

#include <string.h>

char *strcat(char *dest, const char *src);

Description

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 concatenated 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-terimated.

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.

Example

#include <assert.h>
#include <string.h>

int main() {
    char src[7] = "world!";
    char dest1[12] = "hello";
    char dest2[12] = "hello";
  
    // Concatenate the entire src string to dest1.
    strcat(dest1, src);
    assert(strcmp(dest1, "helloworld!") == 0);

    // Concatenate 5 characters from src to dest2.
    strncat(dest2, src, 5);
    assert(strcmp(dest2, "helloworld") == 0);
}

Return Value

Upon completion, the strcat() and strncat() functions return a pointer to the resulting string dest.

See Also

strcpy(), strncpy(), strcmp()