在下面的代碼:在對象的動態數組上調用delete []不會釋放內存?
int main(int argc,char * argv[]){
int * ptr;
ptr = 0; // tried also with NULL , nothing changes
ptr = new int[10]; // allocating 10 integers
ptr[2] = 5;
ptr[15] = 15; // this should cause error (seg fault) - but it doesn't
cout << ptr[2] << endl;
cout << ptr[15] << endl; // no error here
delete [] ptr;
cout << ptr[2] << endl; // prints the value 5
cout << ptr[15] << endl; // prints the value 15
}
執行的結果是:
5 15 5 15
- 索引號爲15的元素怎麼會存在,如果我只是分配10?
- 爲什麼指針在整個數組被釋放後仍然有值?
我試着用單分配這樣的刪除:
int * ptr;
ptr = 0;
ptr = new int;
*ptr = 5;
cout << *ptr << endl;
delete ptr ;
cout << *ptr << endl;
的結果是正常的:
5 0
測試用gcc 4.7.2和gcc 4.1.2 fedora 17和另一個平臺(SLC5 - 基於linux的紅帽子),以確保它不依賴於編譯器。我在這裏做錯了什麼?
我想,你應該閱讀接受的答案[這裏](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope)(問題不同有一點,但是可以應用相同的論點) – Lol4t0