Jump to: navigation, search

Description

The strcat() function shall append the null-terminated string pointed to by src to the null-terminated string pointed to by dest. The first character of src overwrites the null-terminator of dest. Source and destination may not overlap.

Return value

The strcat() function shall return the pointer dest; the function has no failure mode and no error return.

Prototype

Declared in string.h

In C90, the prototype is:

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

The C99 prototype is identical but adds the new restrict qualifiers:

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

Implementation

In standard C, this can be implemented as (adjust prototype for C99):

char *strcat(char *dest, const char *src)
{
    char *ret = dest;
    while (*dest)
        dest++;
    while (*dest++ = *src++)
        ;
    return ret;
}

Compilable unit, portable C90 in implementation namespace; public domain; past reviewers: none; current reviews: none

(Flawed) approaches

Due to the (unlikely) possibility that an arbitrary string may have length greater than SIZE_MAX - the maximum value storable in the size_t type - and hence that strlen() won't be able to return the correct value, this code is not portable:

#include <string.h> /* for strlen() */
char *strcat(char *dest, const char *src)
{
    char *ret = dest;
    dest += strlen(dest);
    while (*dest++ = *src++)
        ;
    return ret;
}

Compilable unit, non-portable; public domain; past reviewers: none; current reviews: none

How might such an overlarge string occur in the first place? The Standard doesn't prohibit an implementation from allowing a program to enter the if block:

#include <stdint.h> /* for SIZE_MAX */
#include <string.h> /* for memset */
#include <stdlib.h> /* for calloc */

char *str = calloc(2, SIZE_MAX);
if (str) {
    memset(str, 'x', SIZE_MAX);
    memset(str + SIZE_MAX, 'x', SIZE_MAX - 1);
    str[SIZE_MAX + (SIZE_MAX - 1)] = '\0';
}

Complete snippet, strictly conforming C90; public domain; past reviewers: none; current reviews: none

It's very likely though that in practice an implementation will return a null pointer from the call to calloc()), and if it's known for any implementation that such an oversize string is impossible to generate then the strlen() variant shown above will be safe on that implementation.

References

The C Standard, 7.21.3.1 (C99 numbering)

Personal tools