Search code examples
creturnfreepointer-to-pointer

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;

}

Solution

    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);
    }