采用以下程序:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char a[8] = "Hello, ";
char b[7] = "world!";
strcat(a, b);
cout << a;
return 0;
}
注意 a
和 b
具有与其分配的字符串相同的大小。
documentation表示对于 strcat(a, b)
上类,a
需要足够大以包含连接的结果字符串。
尽管如此,cout << a
显示器 "Hello, world!"
.我是否进入了未定义的行为?
最佳答案
"Am I entering undefined behavior?"
是的。 a[] 末尾的区域已被覆盖。这次成功了,但可能属于其他东西。
这里我使用一个struct来控制内存布局,并进行演示:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
struct S {
char a[8];
char b[5];
char c[7];
};
S s;
strcpy( s.a , "Hello, " );
strcpy( s.b , "Foo!" );
strcpy( s.c , "world!" );
strcat(s.a, s.c);
cout << s.a << endl;
cout << s.b << endl;
cin.get();
return 0;
}
这个输出:
Hello, world!
orld!
代替:
Hello, world!
Foo!
strcat() 遍及 b[]。
请注意,在现实生活中的示例中,此类错误可能要微妙得多,并且会让您想知道为什么完全无辜的函数调用 250 行之后会崩溃并可怕地烧毁。 ;-)
编辑:我还可以建议您改用 strcat_s 吗?或者,更好的是,std::strings:
#include <string>
#include <iostream>
using namespace std;
int main()
{
string a = "Hello, ";
string b = "world!";
a = a + b;
cout << a;
}
关于c++ - strcat 目标数组的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19230452/