Search code examples
carraysfree

free multidimension char** in C not working


I have this functions:

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

Then i do this

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

Why the output is the same before and after the free?? :S

Output:

matrix before free


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


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

I have read all this posts but it doesnt look like it works:

  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

  4. How to properly free char** in C


Solution

  • Why the output is the same before and after the free

    • This is undefined behaviour

    • Once you've freed memory you must remember not to use it any more.

    • After calling

      free(matrix);
      

    you are getting the same output because in your case

    the matrix still points at the same memory.

    However, since matrix is freed, it's now available to be used again

    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

    know more here : click


    To avoid this assign a pointer to NULL whenever you free it. This is a good practice.

    matrix=NULL;