Your str2
variable is not a string, since it does not allocate space for a null terminator. As such, passing it to strcat
results in undefined behavior.
Given what you've seen, the likely situation you've encountered is that str2
is located immediately before str1
in memory. Because str2
is not null terminated, attempting to concatenate it to str1
loops back into str1
and concatenates "first"
back onto str1
. It stops because it does then encounter a null-terminator.
This particular behavior is just one possibility with undefined behavior and should not be counted on to repeat in any predictable manner.
You might also test this by simply printing str2
as a string without the concatenation, though as undefined behavior, it is not guaranteed to do the same again, so this may not be a useful test.
By allowing space for 7 characters in your fix, str2
is initialized with a null-terminator and is a valid string. As such, no undefined behavior is incurred.
If you wish to allocate a string exactly as much space as needed, you can simply not specify the dimensions of the char array.
char str2[] = "second";
This correctly allocates 7 characters.