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


for example codes function file, named fnx.c, func() called main function. how should free temparray here while return double pointer main function @ same time?

    int * * temparray; //global variable in file  static void createpointer(int row, int col) {     int r;     temparray = malloc(sizeof(int * ) * (row));     (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);      (r = 0; r < row; r++) {         (c = 0; c < col; c++) {             temparray[r][c] = oriarray[r + r_offset][c + c_offset];         }     }      //destroy temparray??      return temparray;  } 

  1. in main(), call createpointer()
  2. in main(), call func()
  3. outside func(), when don't need temparray anymore, call destroypointer()

and destroypointer() wrong. you'll have memory leaks. should :

static void destroypointer (int row) {     (int r = 0; r < row; r++)     {        free(temparray[r]);      }     free(temparray); } 

Comments