c++ - strcat 目标数组的大小

标签 c++ c strcat

采用以下程序:

#include <iostream>
#include <cstring>

using namespace std;

int main()
{
    char a[8] = "Hello, ";
    char b[7] = "world!";

    strcat(a, b);

    cout << a;

    return 0;
}

注意 ab具有与其分配的字符串相同的大小。

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/

相关文章:

c++ - 防止 Ctrl-C 关闭程序

c++ - 查询类的静态成员变量

c - GDB 无法识别某些 C 函数

c - 这些字符串是否为 fopen() 正确连接?

c++ - 填充结构 tm

c++ - g++ std::variant 似乎无法支持具有 std::atomic/std::mutex 变量成员的用户类(带有详细信息/代码)

c - 如何使用 sscanf 解析 C 中的程序参数

c - Visual Studio 2017 是否对 C 进行语法检查?

c - 如何在换行符 "\t"之前将字符 "\n"添加到字符串中

c - 与 C 中的 strcat 函数作斗争