strcat implementation

skydoor picture skydoor · Mar 21, 2010 · Viewed 50.1k times · Source

I tried to implement the strcat by myself, and I found the strcat implementation from Wiki like this......but when I use it, there is segmentation fault.

What's wrong with the code below?

char *
strcat(char *dest, const char *src)
{
    size_t i,j;
    for (i = 0; dest[i] != '\0'; i++)
        ;
    for (j = 0; src[j] != '\0'; j++)
        dest[i+j] = src[j];
    dest[i+j] = '\0';
    return dest;
}

Answer

Pavel Radzivilovsky picture Pavel Radzivilovsky · Mar 21, 2010

the code is okay.

Looks like you have a problem in the calling code.

Did you remember to allocate enough memory for the target string?