mardi 5 mai 2015

Deleting pointer to array

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++)

Aucun commentaire:

Enregistrer un commentaire