What is up.
RSS icon Email icon Home icon
  • delete[]

    Posted on March 16th, 2005 Alan 2 comments

    In C++, you free memory that was allocated using the keyword new, with the keyword delete.  If you allocated an array using:

    char* pDataChars = new char[100] ;
    char* pDataObjs = new CString[100];

    then you include brackets in the call to delete:

    delete[] pDataChars;
    delete[] pDataObjs;

    If you wrote:

    delete pDataChars;
    delete pDataObjs;

    the compiler would not complain but the results may or may not be reliable.

    You should make it a habit of always matching up new[] with delete[] and your code will be more robust and portable.

    So why the brackets?  As I understand it, when calling delete on a pointer, the compiler does not know whether is is a pointer to a single object or an array of those objects.  A pointer to an array of objects, after all, is the same as a pointer to the first item of that array.

    The brackets serve as a "hint" to the compiler so that it knows the structure of the allocated block of memory.  A user should NOT think of delete as equivalent to free.  You should not assume anything about the implementation of new or the record structure on the heap of the allocated memory.

    Update: Here are the details of a scalar/vector new/delete implementation

     

    2 responses to “delete[]”

    1. Prishanthy Wilson

      Interesting link regarding mismatching new/delete:

      http://blogs.msdn.com/oldnewthing/archive/2004/02/04/67384.aspx

    2. Prishanthy Wilson

      http://blogs.msdn.com/oldnewthing/archive/2004/02/04/67384.aspx

    Leave a reply

    You must be logged in to post a comment.