在《剑指offer》的一书提供的源代码中看到这样的代码片段
unsigned int Sum_Solution1(unsigned int n)
{
Temp::Reset();
Temp *a = new Temp[n];
delete []a;
a = NULL;
return Temp::GetSum();
}
其中 指针 a 被delete后又有 a = NULL,我试着在codeblocks上写了一下
但是在VS2013中就报错
能请大家帮忙给看看吗
PHP中文网2017-04-17 13:47:37
delete and new appear in pairs, and the error is caused by delete and has nothing to do with assigning values to pointers.
You set it before
char *a = "test1";
The a here is a pointer to the constant area and cannot be deleted.
The example in the original code is the array usage of new and delete, so the exception in Visual Studio is correct.
If the deleted object is not new, the resulting behavior is undefined, so CodeBlocks does not report an error.