I can't figure out why the following C++ code compiled in VS2013 results in a crash.
#include "stdafx.h"
class A {};
void main()
{
A** arr1 = new A*[5] { new A(), new A(), new A(), new A(), new A() };
delete[] arr1;
A** arr2 = new A*[] { new A(), new A(), new A(), new A(), new A() };
delete[] arr2;
}
The first array gets initialized and deleted correctly, but the second results in a "%Filename%.exe has triggered a breakpoint" exception on the delete[] arr2 line followed by a debug assertion:
File: f:\dd\vctools\crt\crtw32\misc\dbgheap.c
Line: 1322
Expression: _CrtIsValidHeapPointer(pUserData)
The difference between these two arrays is quite obvious: one has an explicitly specified length, the other doesn't. But isn't the compiler supposed to be clever enough to determine the length from the number of items in the following initializer list? Because it does that just fine if the array consists of raw objects (i.e. A* arr = new A[] { A(), A(), A() }).
Please point me to what I'm doing wrong or explain the reason behind this.
Disregard the memory leaks from the array items. They get deleted in the real program, this one was quickly thrown together for a demonstration. The crash occurs either way.
deleteeach index and thendelete[]the array pointer itself.. -- Sorry did not seedisregard the memory leaks. Weird, the second declaration of the array doesn't compile for me in Mingw 4.8.1.new A*[]is even legal...