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.

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.

Answers


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


Need Your Help

AJAX POST Request returning 404 on Spring MVC

java json jquery spring-mvc spring-3

I'm working on a project where I need to submit a JSOn object using AJAX to Spring controller. But I'm getting 404 on submission. Please, can somebody tell me what the problem is:

x64 MOV, JMP instruction crashes program

c++ c++11 inline-assembly hotpatching

I'm learning how to hotpatch functions and I have the following code which works fine in 32-bit programs. However, I'm trying to get it to work in 64-bit programs as well but it just crashes.