array not deleting

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 = new int [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:
1
2
3
4
5
int* ptr = new int;
*ptr = 20;
delete ptr;

cout << *ptr;  // <- ? 


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 still smelling a memory leak. You deleted, or attempted to, temp. But you didn't do anything about v.
Yeah that too. 2 new[]s and only 1 delete[]. Definitely a leak.
With correct index, it does delete. Thanks a lot.
It was deleting before, too =P

But yeah. ;)
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.
on similar note, why does this not change v[1] to 20?

void f(int * & a)
{
int * temp; temp = new int [2];
temp[0] = 2;
temp[1] = 20;
a = temp;
}

int main ()
{
int v[2] = {1,1};

f(v);
cout <<v[1]<<endl; // v[1] = 1 not 20

}

Last edited on
void f(int &a[])
Topic archived. No new replies allowed.