Hack of the day: Safe delete
February 3, 2011

If you free up memory in C++, you should also set the pointer to NULL. If you double delete memory, your application will crash!

Because I’m a lazy coder, I’m using a macro or template in nearly every of my C++-Projects to get rid of it:

template<class T>
inline void safeDelete (T*& p) { 
    delete p; 
    p = NULL; 
  1. shurcooL (2011-02-04 03:01)

    Keep in mind this isn’t thread-safe.

  2. Campbell (2011-02-20 10:17)

    I don’t think this is safe. Shouldn’t you check if the pointer is null before you delete it? This way you won’t cause a crash by accidently calling SafeDelete twice.Eg:template<class T>inline void safeDelete (T*& p) { if ( p != NULL ) { delete p; p = NULL; }}

  3. dimayak (2011-02-22 21:46)

    Campbell, you can safely delete null pointer without any crashes

Add your comment now