The delete and new operators in C++ are much better than the malloc and free functions of C. Consider using new and zap (delete function) instead of malloc and free as much as possible.
To make delete operators even more cleaner, make a Zap() inline function. Define a zap() function like this:
// Put an assert to check if x is NULL, this is to catch // program "logic" errors early. Even though delete works // fine with NULL by using assert you are actually catching // "bad code" very early // Defining Zap using templates template <class T> inline void zap(T& x) { assert(x != NULL); delete x; x = NULL; } template <class T*> inline void zap(T*& x) { assert(x != NULL); delete x; x = NULL; } // For delete array template <class T> inline void zaparr(T& x) { assert(x != NULL); delete [] x; x = NULL; }
The zap() function will delete the pointer and set it NULL. This will ensure that even if multiple zap()'s are called on the same deleted pointer then the program will not crash. For example -
zap(pFirstname); //zap(pFirstname); // no core dumps. Because pFirstname is NULL now //zap(pFirstname); // no core dumps. Because pFirstname is NULL now zap(pLastname); zap(pJobDescription); int *iiarray = new int[10]; zaparr(iiarray);
There is nothing magical about this, it just saves repetative code, saves typing time and makes programs more readable. The C++ programmers often forget to reset the deleted pointer to NULL, and this causes annoying problems causing core dumps and crashes. The zap() takes care of this automatically. Do not stick a typecast in the zap() function -- if something errors out on the above zap() function it likely has another error somewhere.
Also my_malloc() , my_realloc() and my_free() should be used instead of malloc(), realloc() and free(), as they are much cleaner and have additional checks. For an example, see the file "String.h" which is using the my_malloc() and my_free() functions.
WARNING : Do not use free() to free memory allocated with 'new' or 'delete' to free memory allocated with malloc. If you do, then results will be unpredictable.
See the zap examples in example_String.cpp.