Many times, a program crashes due to multiple deletes on the same pointer. In some cases, this is due to a programming error that can be removed. There are situations, however, where it may be unclear whether to delete a pointer or not. Let’s consider the code given below:
void function(){ char *pcMemory; try { pcMemory = new char[25];//allocate memory //perform some operations delete[] pcMemory; //delete memory } catch(...){ } //perform some operations //Delete pcMemory or Not??}
If everything works fine, pcMemory will be properly deleted at the end of the try block. But if one of the operations between allocation and deletion throws an exception, pcMemory will remain allocated. At the end of function, it’s not known whether to delete pcMemory or not. Deleting it may cause a double deletion followed by a crash. Similarly, if it’s not deleted, it may result in a memory leak. The trick is to always set the memory pointer to NULL after deletion:
void function(){ char *pcMemory; try { pcMemory = new char[25];//allocate memory //perform some operations delete[] pcMemory; //delete memory pcMemory = NULL; } catch(...){ } //perform some operations delete[] pcMemory; //Deleting NULL is legal and not an error or crash.}
Because a delete statement can easily be put at the end of function, whether pcMemory has been deleted or not, deleting NULL is absolutely safe.