Skip to main content

C++ delete vs delete[]

In C++ both delete and delete[] are used deallocate storage allocated via dynamic meory allocation. However delete is used to deallocate storage of a single object and delete[] used to deallocate storage of an array.

If you allocate memory using new keyword make sure to deallocate memory using delete keyword to avoid memory leaks. If you allocate an array of memory using new[] deallocate memory using delete[] keyword.

If you allocate memory using new[] and use delete for deallocation in C++ it is undefined behavior. As per my experience compiler will not give any error, however there will be memory leak as only the first object will be deallocated.

Also, it is undefined behavior for both delete and delete[] if the value of the pointer in invalid.

Both of these operations are safe if the pointer is eqaul to NULL/nullptr. So as a best practice it is good to assign nullptr once the memory is deallocated to avoid undefined behavoir.

Few more important points on delete and delete[];
  • It will give an error if you try to delete stack allocated variable or a non pointer object. 
  • It is not recommended to delete a void pointer as it is undefined behavior (most compilers will give a  warning). Also, the destructor will not get called if you delete a void pointer. Run and check the below example.