954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Delete keyword question?

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;
}
rom87
Newbie Poster
10 posts since Mar 2009
Reputation Points: 10
Solved Threads: 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.

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

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;
}
Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You