Search code examples
carraystypesfreedealloc

Can't deallocate 2D array with free in C


im trying to dealloc a Matrix i've created in MatrizCrea(n,m) using MatrizLibera(v), but both of the free() are telling me that there is a conflict of types.

I've done this code following severa sources, so I'm quite unsure of why this error is happening.

header.h

typedef struct Matriz {int n, m, **d;} Matriz;

Matriz MatrizCrea(int n, int m);
void MatrizLibera(Matriz v);



body.c

Matriz MatrizCrea(int n, int m) {
    Matriz mat;
    mat.n = n;
    mat.m = m;

    int ** val = (int*)malloc(n*sizeof(int*));
    int i = 0;
    for (; i<n;i++) {
        val[i] = (int*)malloc(m*sizeof(int*));
    }

    mat.d = val;
    return mat;
}

void MatrizLibera(Matriz v) {
    int i = 0;
    for (; i<v.n; i++) {
        int *a = v.d[i];
        free(a);
    }
    free(v);
}

How should I be deallocating the 2D array?

Thanks in advance.


Solution

  • Try the following

    Matriz MatrizCrea( int n, int m ) 
    {
        Matriz mat;
    
        mat.n = n;
        mat.m = m;
    
        mat.d = malloc( n * sizeof( int* ) );
    
        int i = 0;
        for ( ; i < n; i++ ) 
        {
            mat.d[i] = malloc( m * sizeof( int ) );
        }
    
        return mat;
    }
    
    void MatrizLibera( Matriz *mat ) 
    {
        if ( mat->d != NULL )
        {
            int i = 0;
            for ( ; i < mat->n; i++ ) 
            {
                free( mat->d[i] );
            }
    
            free( mat->d );
    
            mat->d = NULL;
            mat->n = 0;
            mat->m = 0;
        }
    }
    

    You can also insert a code in function MatrizCrea that will check whether the memory was allocated successfully.