In one of my large projects I encountered problem with deleting arrays that were initialized with no specified size.
I wrote a simple program to check what is going wrong, here is the code
#include "stdafx.h"
class Checker
{
public:
Checker()
:myI(i++){}
virtual ~Checker(){
printf("%i " , myI);
fflush(stdout);
}
private:
int myI;
static int i;
};
int Checker::i = 0;
int _tmain(int argc, _TCHAR* argv[]){
Checker* somePointer;
Checker* anotherPointer;
somePointer = new Checker[4]{
Checker(), Checker(), Checker(), Checker()};
anotherPointer = new Checker[]{
Checker(), Checker(), Checker(), Checker()};
delete[] somePointer;
delete[] anotherPointer; //approach A
delete anotherPointer; //approach B
//in approach C anotherPointer is not deleted
return 0;
}
As You can see anotherPointer is initialized without explicitly defined size.
Of course, only one of the lines marked as approach is active at once.
In approach A output looks like that (< crash> means that program ends unexpectedly)
3 2 1 0 <crash>
In approach B output is
3 2 1 0 4 <crash>
In approach C some time the output is 3 2 1 0 and other time application crashes without printing anything.
As far as I know initialization without specifying size of array ends with different memory allocation, but i don't know how to solve problem with application that crashes at the end and this is my question.
I'm using Visual Studio Pro 2013 Update 4 (MSVC++)
EDIT
In case that there is no solution to that problem other than explicitly specifying size, my question is
Why that "feature" is implemented in MSCC++ at all?
new Checker[]with empty brackets.error C3078: you cannot 'new' an array of unknown bounds.