Fii
Fii

Reputation: 317

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?

Upvotes: 0

Views: 78

Answers (3)

Pete Becker
Pete Becker

Reputation: 76513

new int[10] allocates one block of memory with enough room for ten objects of type int. When you're done with that memory block you need to release it; you do that with delete [], which tells the runtime system that you're finished with that one block of memory.

That's the simple case. When you allocate memory for a type that has a non-trivial destructor, the compiler has to generate code to destroy each of the array elements. In that case, new T[10] allocates one block of memory with enough room for ten objects of type T, and it creates those ten objects using the default constructor. When you're done what that memory block you need to release it; you do that with delete [], which calls the destructor for each of the ten elements, then tells the runtime system that you're finished with that one block of memory.

Upvotes: 0

Barmar
Barmar

Reputation: 782574

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.

Upvotes: 4

Swift - Friday Pie
Swift - Friday Pie

Reputation: 14688

No. Array-type storage is what amounts to contains one object , for which storage was allocated and it should be deallocated accordingly.

From 8.3.4 New

If the allocated type is a non-array type, the allocation function’s name is operator new and the deallocation function’s name is operator delete. If the allocated type is an array type, the allocation function’s name is operator new[] and the deallocation function’s name is operator delete[].

Pointer returned by new expression should be deallocated by delete. new[] expression returns pointer to first element of array and to deallocate array you should use only delete[] operator. Other combinations yield UB and the use delete on element of array is UB.

Upvotes: 2

Related Questions