gpt4 book ai didi

c++ - 为什么 std::strcpy 仍然适用于像 char copyTo[0] 这样的目的地?

转载 作者:行者123 更新时间:2023-11-28 01:20:10 24 4
gpt4 key购买 nike

这个测试居然通过了,看起来目的地的大小并不重要,只要它是一个指向char数组的有效指针即可。

我实际上预计测试会失败,任何解释将不胜感激。

#include "gtest/gtest.h"

#include <string>

using namespace std;

TEST(practice, book) {
const char * copyFrom = "Hello World!";
char copyTo[0]; //TODO: why it works?

std::strcpy(copyTo, copyFrom);

EXPECT_STREQ("Hello World!", copyTo);

std::cout << copyTo << std::endl;
}

最佳答案

I actually expected the test to fail

为什么?

任何类型的失败都意味着以下两种情况之一:

  • 由于未定义的行为导致崩溃

  • std::strcpy 对其参数执行一些检查时引发的其他错误

std::strcpy 不对其参数执行任何检查(由于性能原因)并且它明确声明它是 undefined behavior 尝试使用它来编写到一个不够大的缓冲区。这意味着崩溃(或其他故障迹象)也可能发生,但由于未定义的行为,而不是由于确定缓冲区不正确的某些诊断。

[...] it seems that the size of the destination doesn't matter, as long as it is a valid pointer to a char array

为了代码的编译运行? 。为了代码格式正确? 没有

您的代码表现出未定义的行为,并且无法预测其结果。它可能看起来可以工作,也可能会崩溃,它可能看起来只在星期五工作,或者它可以开始无限地向 stdout 输出内容。

记住 - 您不能期望任何表现出未定义行为<的代码/em>.

关于c++ - 为什么 std::strcpy 仍然适用于像 char copyTo[0] 这样的目的地?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56720012/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com