Next Previous Contents

4. C++ Zap (Delete) command

The delete and new commands in C++ are much better than the malloc and free functions of "C". Consider using new and zap (delete command) instead of malloc and free as much as possible.

To make delete command even more cleaner, make a Zap() command. Define a zap() command like this:


/* 
** Use do while to make it robust and bullet-proof macro.
** For example, if "do-while" is NOT used then results will be
** something else just as in -
** if (bbint == 4)
**              aa = 0
** else
**              zap(aptr);  // Problem!! aptr will be always set to NULL 
*/

#define zap(x) do { delete(x); x = NULL; } while (0)

The zap() command 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);

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() command -- if something errors out on the above zap() command 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 "mychar.h" which is using the my_malloc() and my_free() functions.


Next Previous Contents