free a pointer to pointer variable

Hi, i'm trying to free a **pMatrix variable. (pointer to pointer). I have tried this code

for(i=0;i<=2*Nxfm+2*Nyfm;i++)
{
for(j=0;j<=2*Nxfm+2*Nyfm;j++)
{
free(pMatrix[i]);
}
}
free(pMatrix);

which is given in many turorials but this gives me an error (windows detect an iterruption point). why? my matrix is (2*Nxfm+2*Nxfm)x(2*Nxfm+2*Nxfm)=rows x columns.

Can anybody tell me where's the error? thanks in advance!
Sorry, the original code is

for(i=0;i<=2*Nxfm+2*Nyfm;i++)
{
free(pMatrix[i]);
}
free(pMatrix);
This is C++ so you should use "new" and "delete" for dynamic memory allocation. Also use CODE tags.

new:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int ** pMatrix = NULL;

pMatrix = new int* [MAX1];
if (NULL != pMatrix)
{
   for (int i=0; i < MAX1; i++)
  {
      pMatrix[i] = new int[MAX2];
      if (NULL == pMatrix[i])
      {
          //allocation failed cleanup the previously allocated memory
      }
  }
}
else
{
    //Allocation failed
}


Delete:
1
2
3
4
5
6
7
8
9
10
if (NULL != pMatrix)
{
    for (int i = 0; i < MAX1; i++)
   {
        if (NULL != pMatrix[i])
            delete [] pMatrix[i];
   }

   delete [] pMatrix;
}


Or there abouts, didn't compile this. But you'll get the idea.
Last edited on
I think i dind't get the idea... this code fails. why you put the condition NULL != pMatrix?? What if I use calloc?
In my program the error is in the delete statement. Maybe is the compiler? I use visual c++ 2008.
- You can delete NULL pointers without any problem (nothing will happen). No need to check for NULL there.

- new doesn't return a NULL pointer like malloc does anyway, instead it throws an exception if allocation failed. The only time it returns a null pointer is if you use the nothrow version (which you're not using here)

- iharrold is right, if you're using C++ you should get in the habit of using new[]/delete[] instead of malloc/calloc/free. new/delete call ctors/dtor, malloc/free do not.

- nested new multidimensional arrays are evil. Obligatory link: http://cplusplus.com/forum/articles/17108/

- don't assume it's a compiler problem.

- it's difficult for us to show proper cleanup code without seeing the allocation code. Pretty much, the cleanup code should look exactly the same, but backwards.
Topic archived. No new replies allowed.