void f(int * & a)
{
int * temp; temp = new int [2];
temp[1] = 2;
temp[2] = 20;
a = temp;
delete [] temp;
}
int main ()
{
int * v = NULL; v = new int[2];
v[1] = 1; v[2] = 1;
f(v);
cout <<v[2]<<endl; // returns 20 !
}
I thought deleting temp would delete the array but 'a' still points to it. confused. Please clarify.
For starters, array indexes are zero based. So you are stepping out of bounds in your arrays:
1 2 3
int * temp; temp = newint [2];
temp[1] = 2;
temp[2] = 20; // WRONG -- [2] does not exist, only [0] and [1] exist
As for your actual question... delete doesn't actually remove the physical memory from the machine. The pointers still point to real memory. It's just that what resides at that memory no longer is allocated to your buffer.
A simplified version of your problem to illustrate:
What will this print? The answer is: "It's undefined. It could print anything". You might get 20, or you might get -97823972, or it might segfault. There's no way to know.
At the time we print it, ptr no longer points to valid memory, therefore "anything goes".
I'm guessing you're being fooled by it. I suggest you run the program inside of valgrind; you'll find, I think, that you're not de-allocating some of your heap.