我試圖釋放同一個指針兩次,但失敗了,但是如果我按照相同的步驟使它不爲NULL,代碼運行正常。兩次釋放同一個指針不給錯誤,如果我讓指針爲空
#include <iostream>
struct MyClass {
MyClass() {std::cout << "Allocated and Constructed" << std::endl ;}
};
int main() {
// allocates and constructs five objects:
MyClass * p1 = new MyClass[5];
delete[] p1;
delete[] p1; // The code will succeed if I comment this line of code
p1=NULL;
delete[] p1;
delete[] p1;
return 0;
}
我看到一個很好的回答這個問題,但What happens when you deallocate a pointer twice or more in C++?什麼使得它運行,如果我讓NULL,不應該是相同的行爲要遵循兩種情況?
刪除NULL是明確的和什麼也不做。 – molbdnilo
[是否可以安全地刪除NULL指針?](http://stackoverflow.com/questions/4190703/is-it-safe-to-delete-a-null-pointer) –