Search code examples
cpointerscodeblocksfree

C - program crashes when using free function


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 :

Using free() function in C

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

equal Directions

Directions are equal in and out the function, so I don't think I'm trying to free an invalid pointer


Solution

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