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;
}
I get the following error at runtime: Unhandled exception at 0x5B987508 (msvcr110d.dll) in test212.exe: 0xC0000005: Access violation reading location 0xCDCDCDC1.
It’s obviously a memory problem, but can you please tell me what happens in this example of code?
new A[20]calls the default constructor, and you don’t initializenamein the default constructor. You can’t assume that it will be set toNULLfor you. In the absence of initialization,delete[] namehas undefined behaviour.