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

时间:2015-02-19 22:08:49

标签: c++

我只是想复制“临时”中的内容。进入' 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;
}

2 个答案:

答案 0 :(得分:1)

Praetorian击中头部。 “你缺少的重要规则是使用std::string”。像strcpy_s这样的旧C函数众所周知地令人难以置信地不可靠,这就是不再这样做的重点。所以不要这样做。使用std::string

答案 1 :(得分:0)

上面的代码片段导致“Debug Assertion failed”运行时错误。

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

所以答案是strcpy_s(p,len + 1,temp);在你的情况下会很好。

相关问题