Monday, December 14, 2009

Diffrence B/W delete and delete[]

Overview: delete is a operator in C++ , which can be overloaded .
What it does ??
IT frees the Dynamically Allocated Memory pointed by pointer and also calls Destructor for same pointer type .

Example :
*ptr=new ;
delete ptr;                     // frees and call desturctor also

delete [] is to free dynamically allocated Array , It also calls Destructor for all the objects contained by Array .It is used in conjunction of new[].

Example:
* ptr = new (10);                   //pointer to an array of 10 obj
then to free memory equal to 10 obj
delete []ptr;
NOTE: One can free the memory even by "delete ptr ;" But it
will free only the first element in Array memory.other Nine will stay as it is .
Also Desructor for the first Element will be called for sure .
 

Example
employee *arptr = new employee[3];

for (int j = 0 ;j < 3 ;j++) 


arptr[j].setvalue(j); 
}
//delete [] arptr;                              // frees and call all Dtors employee
* cloneptr = arptr; 
delete arptr;                                  // only delets First location and call Dtor for First obj 
cloneptr++;
cloneptr->gt;show(); // works fine able to see Variable of 2 nd OBJ NO core dumps

Verdict : This calling delete for array has different behaviour as per implementation   some times it corrupts HEAP and some time it jus call one destructor and free First Element . 
------------------------------------------------------------------------------------
FAQ on new and Delete 
Q what if we delete a ptr pointing to NULL? 
       No issues safe 
Q What if we call delete twice for same pointer ? 
     This is catastrophic . 
Q What is Placement new and placement delete  .
Q Why after Placement delete we need to call Destructor Explicilly?

2 comments:

Followers