Noam Chai Noam Chai - 1 year ago 72
C++ Question

destructor crashing and array of pointers in cpp

I made a class named 'cell'. Inside this class there is an array of cell pointers. the header looks like this:

class cell
{
public:
cell();
cell *c[8];
void creatcells();
virtual ~cell();
..

}


and the cpp file looks like this:

cell::cell()
{
//ctor
for(int i=0;i<8;i++)
{
c[i]=NULL;
}

}



void cell::creatcells()

{
cell c1,c2,c3,c4,c5,c6,c7,c8;

c[0]=&c1;
c[1]=&c2;
c[2]=&c3;
c[3]=&c4;
c[4]=&c5;
c[5]=&c6;
c[6]=&c7;
c[7]=&c8;
}

cell::~cell()
{
for(int i=0; i<8; i++)
{
if (c[i]!=NULL)
{
delete c[i];
}
}
delete[] c;

}


But each time the programe ends , it crashes, why?
I tried without 'if (c[i]!=NULL)' but this is not helping. Only without the for loop the code ends perfectly but I know this must be deleted also.
I think i wrote the destructor ok, no?

Answer Source
void cell::creatcells()
 {
   cell c1,c2,c3,c4,c5,c6,c7,c8;

   c[0]=&c1;
   c[1]=&c2;
   ...

All of the above cell objects are automatically destroyed at the end of createcells().So delete c[i]; in destructor is UB.What you want is

 c[0]= new cell();
 c[1]= new cell();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download