Size strcat Destination Array

Run the following program:

#include <iostream> #include <cstring> using namespace std; int main() { char a[8] = "Hello, "; char b[7] = "world!"; strcat(a, b); cout << a; return 0; } 

Note that a and b are the same size as the rows assigned to them.

The documentation states that for strcat(a, b) to work strcat(a, b) a must be large enough to contain a concatenated result string.

However, cout << a displays "Hello, world!" . Am I entering undefined behavior?

+6
source share
5 answers

"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> #include <iostream> using namespace std; int main() { string a = "Hello, "; string b = "world!"; a = a + b; cout << a; } 
+11
source

Am I entering undefined behavior?

Yes.


If the documentation states that " a must be large enough to contain a concatenated result string," why don't you just believe it? What can be doubted?

+3
source

In your program, the array a not large enough to contain the result. Therefore, your code is incorrect and must be fixed. According to the standard, you really enter undefined behavior, which means that it may work, or it may not ...

+2
source

strcat does what the tin visa says. copies b to the end without any care as to which data already exists. Since both variables are on the stack one by one, they work. But try

 #include <iostream> #include <cstring> using namespace std; int main() { char a[8] = "Hello, "; int i = 10; char b[7] = "world!"; strcat(a, b); cout << a << i; return 0; } 

And you will probably get unexpected result, since your stack was damaged by strcat

+2
source

This is correct .... The behavior is undefined. Just because you received this answer does not mean that it will not be broken the next time, since array a too small.

+1
source

Source: https://habr.com/ru/post/955429/


All Articles