[Solved] C – program crashes when using free function


The errors in the code is:

  • M == NULL is not a valid way to check if malloc is succeeded. You should use (*M) == NULL because the value is assigned to (*M), not M.
  • The loop condition in ReservarMemoriaMatriz i<=m seems wrong. It should be i<=n.
  • You forgot to free (*M)[n] in LiberarMemoriaMatriz.

Corrected code:

void LiberarMemoriaMatriz(double*** M,int n){
    int i = 0;
    if(M == NULL) return;
    for(i=0; i<=n; i++){
        free((*M)[i]);
    }
    free(*M);
}

int ReservarMemoriaMatriz(double*** M, int n, int ,){
    int i = 0;
    if(M == NULL) return 0;
    (*M) = malloc((n+1)*sizeof(double*));
    if((*M) == NULL){
        return 0;
    }
    for(i = 0; i<=n; i++){
        (*M)[i] = malloc(m*sizeof(double));
        if((*M)[i] == NULL){
            /* free what is allocated before failing */
            for(i--; i>=0; i--) free((*M)[i]);
            free(*M);
            return 0;
        }
    }
    return 1;
}

1

solved C – program crashes when using free function