1

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?

trincot
  • 317,000
  • 35
  • 244
  • 286
Kalindu
  • 111
  • 2
  • 9
  • 2
    You're not assigning the results of the mallocs in the loop anywhere. You can't free them if there's no variables holding the pointers. You need `pArray[i] = malloc(...);`. – Barmar Apr 18 '22 at 19:30
  • 2
    `What can I free twice in this case?` What? You don't free things twice. – tkausl Apr 18 '22 at 19:30
  • [don't cast malloc](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Barmar Apr 18 '22 at 19:31
  • Once you fix that problem, you just free everything in reverse. Loop over the array freeing each element, then free `pArray`. – Barmar Apr 18 '22 at 19:32
  • The inner loop should be `malloc(pColumns*sizeof(int));` (one acceptable method). You `malloc` space for the thing you're pointing to, which inside the loop is `int` type, not `int*`. – yano Apr 18 '22 at 19:34

1 Answers1

0

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 );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335