Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming

C++ Tip: Aware of the confusion between delete with delete[]

5.00/5 (3 votes)
13 Aug 2011CPOL 7.8K   3  
It is a bad idea to treat built-in types differently than programmer defined classes. If you delete a dynamically allocated array of a built-in type without the brackets the memory buffer may go away just fine. This is not guaranteed. The VS2008 runtime throws an exception. There is a...
It is a bad idea to treat built-in types differently than programmer defined classes.

If you delete a dynamically allocated array of a built-in type without the brackets the memory buffer may go away just fine. This is not guaranteed. The VS2008 runtime throws an exception.

There is a more important difference.

The delete array operator delete [] calls the destructor on each of the array elements. The singleton delete does not. it will only call the destructor on the first.

If the compiler and testing don't catch it you could wind up with a nasty bug. Your time and your users' time cost more than any trivial possible runtime difference, which the compiler will optimize away anyhow. Don't give yourself bad habits. Treat built-in types like any other.

This test program shows the destructor being called for each array element on delete [].

class test
{
private:
    static int m_instance;
public:
    test() { ++m_instance; }
    ~test ()
    {
        printf ( "test destructor %d\n", m_instance-- );
    }
};

int test::m_instance = 0;

int main ()
{
    test *t = new test[10];

    delete [] t; // calls the destructor ten times
    t = NULL;

    t = new test[10];
    delete t;    // undefined behavior
    t = NULL;

}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)