devxlogo

Avoid Deleting a Pointer More Than Once

Avoid Deleting a Pointer More Than Once

The results of deleting an object more than once are undefined. However, if code modifications are impossible (when a third party code is used, for example), a temporary workaround to this bug is assigning a NULL value to a pointer right after it has been deleted. It is guaranteed that a NULL pointer deletion is harmless.

 String * ps = new String;//...use psif ( TrueCondition ) {		delete ps; 	ps = NULL; //safety-guard: further deletions of ps will be harmless}//...many lines of codedelete ps; //a bug. ps is deleted for the second time. However, it's harmless

Please note that this hack is not meant to replace a thorough code review and debugging; it should be used as a transitory band-aid.

devx-admin

Share the Post: