开发者

struct with list<..> in 2 dim. dynamic array segfaults on delete

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.

开发者_JAVA百科

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.


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

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


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

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


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;
}


i think delete [] myAr; should work fine

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜