When calling the function strcat
, it is required that you pass as the first argument a pointer to a memory buffer that is large enough to store the concatenated string.
In your case, the concatented string has a length of 6 characters ("onetwo"
), so the memory buffer must have a size of at least 7 characters (including the terminating null character). However, in your case, the memory buffer has a size of only 4 characters, which is insufficient. Therefore, your program is invoking undefined behavior, which means that anything can happen. This includes the behavior that you describe in the question.
To fix the problem, you must make the array s1
at least 7 characters long:
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char s1[7] = "one";
char s2[4] = "two" ;
strcat(s1, s2);
cout << s1 << endl;
cout << s2 << endl;
return 0;
}
This program has the desired output:
onetwo
two