Strcat () crashes when using the same array as both parameters

char r[40];
strcpy(r,"abcdef");
strcat(r,r);

My program crashes in the third line?

Replacing strcat (r, r); by strcat (r, "abcdef"); works great though ... why is this?

+3
source share
4 answers

strcat()reads from the input and copies it to the output, until it finds a terminator \0at the input. By specifying the same array for both input and output, you change the input while reading.

You will need to check the specific implementation of your compiler strcat(), but if you follow through a simple implementation, as shown below, you should see why your code will work after a while:

char *strcat(char *dest, const char *src )
{
    char *ret = dest;
    if (dest && src)
    {
        while (*dest != 0)
            ++dest;
        while (*str != 0)
            *dest++ = *src++;
        *dest = 0;
    }
    return ret;
}

while (*dest != 0) dest \0. while (*str != 0) a, , . , , , \0 .

0

strcat(3):

strcat() src dest, ('\ 0') dest, . , dest .

+3

, strcat char * r. r, , , ( , ).

- - strncat (r, r, strlen (r)), R .

+2

. "" .

, strcat , , . , .

:

a b c d e f \0

() dest (d) a. dest ,

s           d 
a b c d e f \0

  s           d
a b c d e f a

    s           d
a b c d e f a b

      s           d
a b c d e f a b c

        s           d
a b c d e f a b c d

          s           d
a b c d e f a b c d e

            s           d
a b c d e f a b c d e f

              s           d
a b c d e f a b c d e f a

You can see that the original pointer will not reach its final null byte since it started from the very beginning. In the end, we do not have enough space here.

Since this is a likely scenario, the definition strcatdoes not allow two lines to overlap. Thus, implementations are free to use the underlying implementation.

+2
source