使用Strcpy_s复制动态分配的字符数组

Use Strcpy_s to Copy Dynamically Allocated Char Array

本文关键字:字符 数组 动态分配 复制 Strcpy 使用      更新时间:2023-10-16

我只是想把'temp'中的内容复制到'p'中,但程序在strcopy_s行崩溃。我是不是错过了一些重要的规则?

#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main() {
    char temp[100] = "Coolbeans";
    int len = strlen(temp);
    char* p = new char[len+1];
    strcpy_s(p, len, temp);
    for (int i = 0; i < len; i++)
        cout << p[i] << endl;
    for (int i = 0; i < len; i++)
        cout << temp[i] << endl;
}

禁卫军击中了它的头部。"您缺少的重要规则是使用std::string"。像strcpy_s这样的旧C函数是出了名的难以置信的不可靠,这就是不再做它的全部意义。所以不要这么做。使用std::string

以上代码片段导致"调试断言失败"运行时错误。

 strcpy_s(p, len, temp); //Expression:(L"Buffer is too small" &&0)

所以答案是strcpy_s(p,len+1,temp);对你来说会很好的。