#include <iostream>
using namespace std;
int main ()
{
int myarray [10];
int * ptr1;
ptr1 = new (nothrow) int [10];
cout << "ptr1 = " << ptr1 << endl;
delete [] ptr1;
cout << "ptr1 = " << ptr1 << endl;
int a = 4;
int * ptr2;
ptr2 = &a;
cout << "ptr2 = " << ptr2 << endl;
delete ptr2;
cout << "ptr2 = " << ptr2 << endl;
return 0;
}
It outputs
ptr1 = 0x9941008
ptr1 = 0x9941008
ptr2 = 0xbfca5cd4
Questions:
1) Why the second print of ptr1
still return the same value? The memory is released but the pointer keeps the memory address value?
2) Why the second print of ptr2
doesn't output?
delete
frees the memory, but does not change the value of the pointer. Note however, that the pointer now points to a deallocated area of memory so you should not use it until you reset it.delete
areas of memory which you have previously allocated on the heap with the new
operator.