views:

38

answers:

4

Hey there,

for a little project i wanted to use a struct with an stl container in it. This thingy is then packet into a dynamic 2 dim. array, but when i try to delete it, it segfaults.

Here is the code:

struct cell{
    list<pair<double, double> > alist;

};
int main()
{
   struct cell ** myAr = new cell*[5];
   for(int i = 0; i < 5; ++i)
      myAr[i] = new cell[5];

   for(int j = 0; j < 5; ++j)
      delete myAr[j];
   delete myAr; 

   return 0;
}

Can anyone help me with this? Thanks in advance. Flo.

+6  A: 

Use delete[] for memory allocated with new[]:

for(int j = 0; j < 5; ++j)
    delete[] myAr[j];
delete[] myAr;  
Georg Fritzsche
+1  A: 
int main()
{
   struct cell ** myAr = new cell*[5];
   for(int i = 0; i < 5; ++i)
      myAr[i] = new cell[5];

   for(int j = 0; j < 5; ++j)
      {
       delete[] myAr[j];
       myAr[j] = 0;
       }
   delete[] myAr; 
   myAr = 0;

   return 0;
}
Ando
+1  A: 

i think delete [] myAr; should work fine

fatehmtd
And `delete [] myAr[j]` as well; they were also allocated with `new[]`.
Mike Seymour
+2  A: 

You allocated with new[] so you need to free with delete[]:

for(int j = 0; j < 5; ++j)
      delete [] myAr[j];
   delete [] myAr; 
anon