The difference between using free () on ** my_vector and *** my_vector

I found a function that frees matrix memory:

void free_matrix(int ***matrix, int rows, int cols) {
    int row;

    if (matrix != NULL && *matrix != NULL) {
        for (row = 0; row < rows; row++) {
            free((*matrix)[row]);
            (*matrix)[row] = NULL;
        }
        free(*matrix);
        *matrix = NULL;
    }    
}

I call the method as follows:

int **my_vector = create_matrix(5, 5);
free_matrix(&my_vector, 5, 5);

I don’t quite understand why the author decided to use ***matrix, and not **matrix, because in my other method, where I create the matrix, he does just that:

void fill_matrix(int **matrix, int rows, int cols) {
    int row = 0;
    int col = 0;

    for (row = 0; row < rows; row++) {
        for (col = 0; col < cols; col++) {
            matrix[row][col] = ((row + 1) * 10) + col;
        }
    }
}

int **create_matrix(int rows, int cols) {
    int row;
    int **matrix = malloc(rows * sizeof(int *));

    for (row = 0; row < rows; row++) {
        matrix[row] = malloc(cols * sizeof(int));
    }
    return matrix;
}

There must be a reason why the author decided to use int ***matrixinstead int **matrix.

+4
source share
1 answer

, free_matrix reset NULL . , , undefined, .

, :

/* allocating a pointer to a 2D array matrix[rows][cols] filled to 0 */
int (*matrix)[cols] = calloc(sizeof(*matrix), rows);
/* free the matrix */
free(matrix); matrix = NULL;

, , , , , C99.

***, 2 :

void free_matrix(int **matrix, int rows, int cols) {
    int row;

    if (matrix != NULL) {
        for (row = 0; row < rows; row++) {
            free(matrix[row]);
        }
        free(matrix);
    }    
}

int main(void) {
    int **my_vector = create_matrix(5, 5);
    fill_matrix(my_vector, 5, 5);
    free_matrix(my_vector, 5, 5);
    if (my_vector) {
        /* trying to access the freed data will invoke undefined behavior */
    }
    return 0;
}

my_vector reset to NULL free_matrix, undefined ( - ), , free_matrix reset my_vector NULL, .

+2

All Articles