delete[]

delete[]

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 thoughts on “delete[]

Leave a Reply