The errors in the code is:
M == NULLis not a valid way to check ifmallocis succeeded. You should use(*M) == NULLbecause the value is assigned to(*M), notM.- The loop condition in
ReservarMemoriaMatrizi<=mseems wrong. It should bei<=n. - You forgot to free
(*M)[n]inLiberarMemoriaMatriz.
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