#include <Windows.h> #include <iostream> #include <string> using namespace std; void main(){ char*pch="hello"; char mch[]=" hi"; cout << strcat(pch, mch) << endl; system("pause"); }; 

Do not write about string , need char .

  • In C ++, do not bother with manual memory allocation (yes, this is not easy, you need to count bytes), but use std :: string: int main () {string pch = "hello"; string mch = "hi"; cout << pch + mch << endl; }; - VladD

1 answer 1

If you carefully read the documentation on the function strcat , it turns out that the first parameter is the buffer into which the result of string concatenation will be written. You have this buffer is pch . But declaring it as you did it, you allocated exactly five (six with zero terminator) bytes for this buffer. Trying to add three more bytes to it, you go beyond the boundary of the allocated memory, which translates into a segmentation fault. It would be more appropriate to allocate obviously more memory, like this:

 #include <iostream> #include <string.h> using namespace std; int main(){ char *str = new char[100]; char *pch = "hello"; char mch[] = " hi"; strcat(str, pch); strcat(str, mch); cout << str << endl; return 0; }; 
  • 2
    Wrong copying of the first substring through strcat . Anything can be in the memory area allocated by new . strcat finds the first character of the end of the string by the "target" pointer and copies the string by it. But in your version there can be anything in the memory! And the result may also be unpredictable. Therefore, you need to copy the first substring using strcpy - skegg