Mismatch of new[]/delete or new/delete[]



I had an application where storage was allocated with new[size] and deleted with deleted without specifying the [].  BoundsChecker does not report this as a problem.


If you use new[] on a simple type or an object without a destructor declared  (or for any of its base classes), with the Microsoft compiler, delete will work correctly.  Therefore, BoundsChecker does not catch the mismatch of new[]/delete.  Just because this works properly with the Microsoft compiler, though, does not mean this will work with other compilers.  This is not portable code.  Using new[]/delete (or new/delete[] ) should be avoided.

If you use new[] on an object with a destructor, the new[] will first allocate enough memory for the count (how many objects to allocate for) then the memory for the objects themselves.  The pointer will be adjusted to point to the first object allocated, rather than the count.

Delete[], if there is a destructor, adjusts the given pointer to point to the count.  Delete does NOT, in any case, adjust the pointer to point to the count.  Therefore, using new[] with delete (with destructor), will cause BoundsChecker to flag an 'Invalid argument, operator delete, HANDLE 0x Bad Handle' error (because the pointer is not pointing to the first address that was actually allocated)

Using new[] on an object without a destructor will cause no memory to be allocated for the count, so the pointer will not have to be adjusted.  In this case, using delete should not give an error.  Also, if there is no destructor, the [] on the delete is irrelevant (pointer will not be adjusted), so no error should be flagged.

Old KB# 12311
Comment List
Related Discussions