first, sorry for my bad english jeje. I don't speak it.
I'm having a problem when using free() function to free memory, this is what I have :
I'm using codeblocks on Windows 7. I have around 3 years using dinamic memory allocation and this is the first time I get this problem. There are people that say that the problem is gcc compiler
Directions are equal in and out the function, so I don't think I'm trying to free an invalid pointer
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
.ReservarMemoriaMatriz
i<=m
seems wrong. It should be i<=n
.(*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;
}