C 中的免费多维字符** 不起作用

free multidimension char** in C not working

我有这个功能:

char** init_matrix(int rows, int columns){
    char **matrix = (char **)malloc (rows*sizeof(char *));
    for(int i = 0; i < rows; i++){
        matrix[i] = (char *) malloc (columns*sizeof(char));
        for(int j = 0; j < columns; j++){
            matrix[i][j] = '-';
        }
    }
    return matrix;
}

void show_matrix(char **matrix, int rows, int columns){
    printf("\n\n");
    for(int i = 0; i < rows; i++) {
        for(int j = 0; j < columns; j++)
           printf("|%c|", matrix[i][j]);
        printf("\n");
        for(int j = 0; j < columns; j++)
            printf("---");
        printf("\n");
    }
}

void setValueInMatrix(char** matrix, int row, int column, char value){
    matrix[row][column] = value;
}

那我就这样做

char **matrix = init_matrix(rows, columns);
setValueInMatrix(matrix, solucion->row, solucion->column, solucion->aminoacido);
printf("matrix before free\n");
show_matrix(matrix, rows, columns);
    for(int i = 0; i < rows; i++){
        free(matrix[i]);
    }
    free(matrix);
printf("matrix after free\n");
show_matrix(matrix, rows, columns);

为什么free前后输出一样?? :S

输出:

matrix before free


|-||-||-||H||-||-||-|
---------------------
|-||-||-||P||-||-||-|
---------------------
|-||-||-||P||-||-||-|
---------------------
|-||-||-||H||-||-||-|
---------------------
|-||-||-||-||-||-||-|
---------------------
|-||-||-||-||-||-||-|
---------------------
|-||-||-||-||-||-||-|
---------------------
matrix after free


|-||-||-||H||-||-||-|
---------------------
|-||-||-||P||-||-||-|
---------------------
|-||-||-||P||-||-||-|
---------------------
|-||-||-||H||-||-||-|
---------------------
|-||-||-||-||-||-||-|
---------------------
|-||-||-||-||-||-||-|
---------------------
|-||-||-||-||-||-||-|
---------------------

我已经阅读了所有这些帖子,但它看起来并不奏效:

  1. C: Correctly freeing memory of a multi-dimensional array

  2. how to free c 2d array

  3. how to properly free a char **table in C

输出是相同的,因为 free 将内存标记为空闲(可重复使用)。它不会物理擦除内存。

但是在释放指针后使用指针是代码不应该做的事情,因为你是 reading/writing 可能已分配用于不同目的的内存。

一旦你 "free" 内存,你必须将指针变量(矩阵)视为无效。类似地,对同一个指针调用 free() 两次被称为双重释放,这会使您的程序崩溃或导致其他不良行为。

许多人在释放指针变量后将其设置为 NULL 以防止意外重用。

与 'C' 中的许多内容一样,语言规范允许您违反规则,但后果自负。

Why the output is the same before and after the free

  • 这是undefined behaviour

  • 释放内存后,请记住不要再使用它。

  • 调用后

    free(matrix);
    

你得到相同的输出,因为在你的情况下

the matrix still points at the same memory.

但是,由于 matrix 已释放,现在可以再次使用

Note: the matrix might or might not point the same block after freeing, it's undefined behavior but, in your case it does point the same block

在这里了解更多:click


为避免这种情况,无论何时释放它,都会分配一个指向 NULL 的指针。这是一个很好的做法。

matrix=NULL;