randomGirl
randomGirl

Reputation: 21

How to free a double pointer that need to be returned from the function?

For example this is the codes for a function file, named fnx.c, where func() will be called from the main function. How should I free the TempArray here while return the double pointer to the main function at the same time?

    int * * TempArray; //global variable in this file

static void CreatePointer(int row, int col) {
    int r;
    TempArray = malloc(sizeof(int * ) * (row));
    for (r = 0; r < row; r++) {
        TempArray[r] = malloc(sizeof(int) * (col));
    }
}


static void DestroyPointer() {
    free(TempArray);
    TempArray = NULL;

}

int * * func(int * * OriArray, int row, int col, int r_offset, int c_offset) {
    int r, c;

    CreatePointer(row, col);

    for (r = 0; r < row; r++) {
        for (c = 0; c < col; c++) {
            TempArray[r][c] = OriArray[r + r_offset][c + c_offset];
        }
    }

    //destroy TempArray??

    return TempArray;

}

Upvotes: 0

Views: 1177

Answers (3)

arrfu
arrfu

Reputation: 182

if you want to use this point(TempArray) after called from the main function,you can not destroy it(TempArray).Only when you do not want to use this point datas,you can destroy it. you can test like this:

main()   
{   
  int *p = func(oriArray,row,col,r_offset,c_offset);   

   for (int r = 0; r < row; r++){   
       for(int c = 0; c < col; c++){   
         printf("%d",p[r][c]);   
      }   
   }      

  DestroyPointer();   
}

Hope it helps !

Upvotes: 1

Viktor Simk&#243;
Viktor Simk&#243;

Reputation: 2627

You should free all the rows before freeing up TempArray.

static void DestroyPointer (int row)
{
   for (int r = 0; r < row; r++)
   {
      free(TempArray[r]);
   }
   free(TempArray);
   TempArray = NULL;

}

But You shouldn't destroy the pointer before returning it,
because dereferencing it after that in main will cause undefined behaviour.

Upvotes: 0

Pierre
Pierre

Reputation: 1174

  1. In your main(), call CreatePointer()
  2. In your main(), call func()
  3. Outside func(), when you don't need TempArray anymore, call DestroyPointer()

And your DestroyPointer() is wrong. You'll have memory leaks. It should be something like :

static void DestroyPointer (int row)
{
    for (int r = 0; r < row; r++)
    {
       free(TempArray[r]); 
    }
    free(TempArray);
}

Upvotes: 3

Related Questions