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);
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;
};




相关文章:

  • 2022-12-23
  • 2021-08-27
  • 2022-01-17
  • 2021-07-15
  • 2021-08-07
  • 2021-09-10
  • 2022-01-17
  • 2022-12-23
猜你喜欢
  • 2021-10-12
  • 2022-02-12
  • 2021-08-13
  • 2021-07-25
  • 2021-09-11
  • 2022-12-23
相关资源
相似解决方案