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;
}

Recommended Answers

All 2 Replies

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.

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;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.