是否将多余的数据从std :: string复制到std :: array 未定义行为?

问题描述 投票:0回答:1

我不是要在生产环境中使用此代码,但是对此我有些困惑。我认为它必须是未定义的,但是我运行该代码时没有崩溃。这仅仅是巧合吗?

#include <array>
#include <string>

auto main(int argc, char** argv) -> int {
  // for (int i = 0; i < 1000; ++i) {
  std::array<char, 1000> dst;
  std::string src = "hello world";
  memcpy(dst.data(), src.c_str(), dst.size()); // is this undefined behavior?
  // }
}

c++ memcpy
1个回答
0
投票

我认为它必须是未定义的

是的,这是不确定的行为。 src.data指向12个字符(= 12个字节)的数组,但是memcpy会尝试从中读取1000个字节,因此它超出范围。

但是,我运行了这段代码却没有崩溃

这就是不确定行为的关键。可能发生任何事情。这包括运行完全没有任何问题。

© www.soinside.com 2019 - 2024. All rights reserved.