Search code examples
c++delete-operator

Why is deleting null pointer allowed in C++


I remember reading somewhere that it's neccessary for delete NULL to be a valid operation in C++, but I can't remeber the reason why it should be so. Would someone please remind me?


Solution

  • The rule is not strictly necessary in that the language could exist without it; it is simply a decision made by the standards committee. The null pointer is not a valid memory address. However, I would like to believe that each decision is made for a reason, and those reasons are worth knowing.

    This rule simplifies the management of failure cases and other instances in which a pointer may be null. It is an easy, inexpensive check to make, and it adds appreciable convenience to the language.

    For example, if many conditions exist which would result in dynamic memory allocation, but others also exist which will not, it's convenient to be able to just stick a delete at the end and not worry about it.

    // contrived example
    void foo(int n) {
        char *p = nullptr;
        switch(n) {
            case whatever:
            case something_else:
                p = new char[n];
                break;
        }
    
        // some code...
    
        delete [] p;  // look Ma, no check!
    }
    

    If delete nullptr were illegal then every call to delete would be surrounded by...

    if(ptr)
    

    ...and that would be lame. Since this would be the norm, an essentially mandatory convention, why not just eliminate the need to check entirely? Why require an extra 5 characters (minimum) for every call to delete?