What is the difference between delete and delete[ ]?

The difference is big, and very important to understand. Whenever you create an object in C++ using the new keyword you will have to delete it. Whether you use “delete” or “delete[ ]” really depends on what kind of object you are creating. This is best illustrated by an example:

void foo ( )
{
  string *sp = new string[50];

  string *s = new string;

  delete s; 

  // have to use "[ ]" since sp points to an array of strings:
  delete[ ] sp;

}


Note that we had to use the “[ ]” when deleting the memory that “sp” points to, because the sp pointer points to an array of strings. So, in order to properly remove memory created with a “[ ]”, we have to use the “delete [ ] “.

What happens if you use delete when you should use delete[ ] instead?

This could create a memory leak since using “delete” when “delete[ ]” is required will not properly delete all of the memory in the array.

Hiring? Job Hunting? Post a JOB or your RESUME on our JOB BOARD >>

Subscribe to our newsletter for more free interview questions.