Home > Software engineering >  How to free a malloc 2D array in C initialiszed in this way?
How to free a malloc 2D array in C initialiszed in this way?

Time:04-19

I have declared a 2D malloc array like this in C:

    int** pArray;
    int i;

    pArray=(int**)malloc(pRows*sizeof(int*));
       for(i=0;i<pRows;i  )
         (int*)malloc(pColumns*sizeof(int*));

How can I free this array? I saw on the net that the number of free() should be same as number of malloc() used. What can I free twice in this case?

CodePudding user response:

For starters the allocation is incorrect. This statement

(int*)malloc(pColumns*sizeof(int*));

produces a memory leak.

It seems you mean the following code

int** pArray;
int i;

pArray = (int**)malloc( pRows * sizeof( int* ) );
for( i = 0; i < pRows; i   )
{
     pArray[i] = (int*)malloc( pColumns * sizeof( int ) );
}

Pay attention to that in the statement within the loop there is used the expression sizeof( int ) instead of sizeof( int * ).

You need to free the allocated memory in the reverse order

for( i = 0; i < pRows; i   )
{
     free( pArray[i] );
}
free( pArray );
  • Related