Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to free a malloc 2D array in C initialiszed in this way?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading