char r[40];
strcpy(r,"abcdef");
strcat(r,r);
My program crashes at the third line?
Replacing strcat(r,r); by strcat(r,"abcdef"); works fine though.... why is that?
char r[40];
strcpy(r,"abcdef");
strcat(r,r);
My program crashes at the third line?
Replacing strcat(r,r); by strcat(r,"abcdef"); works fine though.... why is that?
According to strcat(3)
:
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 result.
Late answer. Just wanted to add a little "graphical" explanation.
If you think about how strcat
might be implemented, it initializes a pointer at the first character of the source string and walks through the source character by character until it reaches its null byte. But because the source and destination strings are the same, the following might happen.
Memory starts off like this:
a b c d e f \0
The source (s) and dest (d) pointers both point to the a
on function entry. The dest pointer moves to the end and we get ready to copy
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 source pointer isn't going to reach its terminating null byte, as this got whacked at the beginning. Eventually we'll run out of space here.
So since this is a likely scenario, strcat
's definition does not allow the two strings to overlap. This way implementations are free to use the basic implementation.
strcat()
reads from the input and copies it to the output until it find a \0
terminator in the input. By specifying the same array for both input and output, you are modifying the input while it is being read from.
You would have to check your compiler's particular implementation of strcat()
, but if you trace through a simple implementation like the following, you should see why your code crashes after awhile:
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;
}
After the while (*dest != 0)
loop, dest
is now pointing at the input's \0
terminator. The first iteration of the while (*str != 0)
loop then replaces that terminator with a
, thus causing the loop to no longer stop where it is supposed to. Eventually, the loop will exceed the bounds of the input and start reading surrounding memory, and eventually it will crash if it does not find another \0
byte before hitting invalid memory.