"Am I entering undefined behavior?"
Yes. The area at the end of [] was written over. He worked, this time, but perhaps belonged to something else.
Here I use the structure to control the layout of the memory and demonstrate it:
#include <iostream> #include <cstring> using namespace std; int main() { struct S { char a[8]; char b[5]; char c[7]; }; S s; strcpy( sa , "Hello, " ); strcpy( sb , "Foo!" ); strcpy( sc , "world!" ); strcat(sa, sc); cout << sa << endl; cout << sb << endl; cin.get(); return 0; }
It is output:
Hello, world! orld!
Instead:
Hello, world! Foo!
strcat () staggered around b [].
Please note that in real examples, such errors can be much more subtle and make you wonder why completely innocent functions call 250 lines later crash and horror .; -)
EDIT: Can I also recommend you use strcat_s? Or, even better, std :: strings:
#include <string>
source share