1
class A
{
    char *name;
public:
    A();
    A(char*);
    ~A();
};

A::A()
{

}
A::A(char* s)
{
    int k=strlen(s);
    name=new char[k+1];
    strcpy_s(name,k+1,s);
}
A::~A()
{
    if(name!=NULL)
        delete[] name;
}

int _tmain(int argc, _TCHAR* argv[])
{
    A *v=new A[20];
    delete[] v;
    system("pause");
    return 0;
}

我在运行时收到以下错误:test212.exe 中 0x5B987508 (msvcr110d.dll) 的未处理异常:0xC0000005:访问冲突读取位置 0xCDCDCDC1。 这显然是一个内存问题,但你能告诉我这个代码示例中发生了什么吗?

4

2 回答 2

4

new A[20]调用默认构造函数,并且您不在name默认构造函数中进行初始化。你不能假设它会NULL为你设置。在没有初始化的情况下,delete[] name具有未定义的行为。

于 2013-02-06T19:54:18.083 回答
2

A *v=new A[20]; constructs new A objects via the default constructor A::A(). Your custom constructor A::A(char* s) never gets called and therefore, name is never allocated any memory. When the destructor is called, you are trying to delete[] memory that just isn't there. That results in the exception you see.

于 2013-02-06T19:54:26.323 回答