C++中动态分配的错误

Lyn*_*ing -7 c++ memory-management

#include <iostream>
using namespace std;

char *CopyOf(const char *str);

void main(void)
{
    char *hello = CopyOf("Hello\n");
    cout << hello;
    delete [] hello;
    system("pause");
}

char *CopyOf(const char *str)
{
    char *copy = new char(strlen(str) + 1);
    strcpy(copy, str);
    return copy;
}
Run Code Online (Sandbox Code Playgroud)

程序运行到delete语句时发生我的错误.有什么建议吗?非常感谢你.

Geo*_*ard 6

你应该分配一个chars 数组,如下所示:

char *CopyOf(const char *str)
{
    char *copy = new char[strlen(str) + 1];
    strcpy(copy, str);
    return copy;
}
Run Code Online (Sandbox Code Playgroud)

请注意,我使用了括号,而不是括号.你有什么用括号这样做是初始化一个单一的char与价值strlen(str) + 1.然后通过调用来覆盖1字节缓冲区strcpy.你应该强烈考虑使用std::string; 它可以帮助你摆脱很多这种心痛.

另外,要编译代码,必须添加#include <cstring>.最后,main()应该有返回类型int.