灾难的 char *p = new char(4)
int _tmain(int argc, _TCHAR* argv[])
{
char *p = new char(4);
for (int i = 0; i < 4; i++)
{
p[i] = '0'+i;
}
delete[] p;
p = NULL;
return 0;
}
问题在于哪里?
看正确代码:
// char *p = new char(4);
char *p = new char[4];
上述代码在类的 initialization-list 中尤为难找:
class SomeResource
{
public:
SomeResource(const size_t n) : m_data(new char(n)){} // Disaster! If you access m_data[1..n],
// will causing undefined and obscure behavior.
// But vs 2010 compiler accept this
// code without any warning.
// If you are under Debug mode in vs, there will
// happen debug error just before programming exit.
~SomeResource(){ delete[] m_data; }
private:
// data
char *m_data;
};