Search code examples
c++delete-operator

Why is delete[] not equivalent to calling delete for each element in C++?


Assuming I created an array in the heap:

int* a = new int[10];

Why is this:

for(int i = 0; i < 10; i++) {
        delete (a + i);
}

not equivalent to delete[] a;? Attempting to call delete for any pointer to an element in a results in an memory access violation.

What excactly is the difference?


Solution

  • The pointer you give to delete has to be a pointer that was returned by new. Furthermore, if you use new[] to allocate the object, you have to use delete[] to delete it.

    In many implementations, the metadata that holds information about an allocation (e.g. the size of the allocation) is stored in the memory just before the allocation. So when you pass a pointer to delete, it looks in the preceding memory locations to find this information. When you allocate an array, there's only one of these metadata blocks for the entire allocation. If you try to delete an element inside the array, there won't be any metadata before it, so it won't know how much memory to free.