空终止没有出现在 strcpy-ing 的数组中

null termination didn't appear in the array on strcpy-ing

当我使用 c_str()std::string 转换为 C 风格 字符串时,我没有看到最后一个字符被 null- 覆盖c_str() 应该在这个程序中添加的终止:

#include<iostream>
#include<string>
#include<cstring>

using namespace std;

int main()
{
    string s = "helloworld";
    char c[10];
    strcpy(c, s.c_str());
    cout << c << endl;
    return 0;
}

我想问的是为什么要打印 d(添加到 c),因为我期望 null-termination 在那里。我在这里错过了什么?

您有未定义的行为,"helloworld" 实际上是 "helloworld[=11=]",即 11 个字符。 strcpy 尝试复制包括 NUL 在内的整个字符串,但 c 只能容纳 10 个字符。

strcpy不知道目标数组有多长。它复制直到(并包括)终止的 0 字节。因此,整个字符串 helloworld[=11=] 被复制。请注意,这是 11 个字符,您可能会崩溃。

您的代码有未定义的行为,因为您将字符串复制到其中的数组 c 没有为空终止符分配足够的 space。

您复制的字符数是 10,因此您需要一个 11 的数组来容纳空终止符。

为避免像静态分配数组那样的溢出问题,请改用动态分配:

char *c = new char[s.size()+1];
strcpy(c, s.c_str());
cout << c <<endl;
delete[] c;