0

Why does'nt the delete keyword destroy all of the allocated array and not just the first element.As it is even after the delete[] the second cout still prints out the values of the "t" array.

Any idea ?

int main()
{
int *t =0;
t = new int [10];
t[0] = 3;
t[1] = 7;
cout<<t[0]<<" "<<t[1]<<endl;
delete[]  t; 
cout<<t[0]<<" "<<t[1]<<endl;
cin.get();
return 0;
}
3
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by Ancient Dragon
0

delete frees the memory up for other uses. Just because that memory isn't immediately used after deleting doesn't mean you can safely access it.

0

delete and delete[] don't erase the memory locations, only frees it up for other uses as Narue previously said. The data you stored at that location is still there, but delete invalidated the pointer you had. Its always a good rule-of-thumb to reset pointers to NULL after calling delete or delete[] so that the program doesn't mistakenly attempt to reference the deleted memory location.

int main()
{
int *t =0;
t = new int [10];
t[0] = 3;
t[1] = 7;
cout<<t[0]<<" "<<t[1]<<endl;
delete[]  t; 
t = NULL;
cout<<t[0]<<" "<<t[1]<<endl; // this line will now produce an error
cin.get();
return 0;
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.