C398dd0c2ca7d5281d0a83242a924e76

Is this the correct way to free memory of a multidimensional array in C ?

void freeArray(int **a, int m) {
    int i;
    for (i = 0; i < m; ++i) {
        free(a[i]);
    }
    free(a);
}

Refactorings

No refactoring yet !

55502f40dc8b7c769880b10874abc9d0

black-fox.myopenid.com

December 1, 2009, December 01, 2009 17:21, permalink

No rating. Login to rate!

you may want some more checks (depending on how you work with the array elsewhere)

void freeArray(int **a, int m) {
    int i;
    if (a) {
        for (i = 0; i < m; ++i) {
            if (a[i]) {
                free(a[i]);
            }
        }
        free(a);
    }
}
A07f8d0f843a8ec4dad62bc9e87511ba

kulp

December 3, 2009, December 03, 2009 21:52, permalink

No rating. Login to rate!

black-fox: it is never necessary to check for (x == NULL) before doing free(x). free(NULL) is guaranteed by the C standard to do nothing. However, your first check "if (a)" may be a good idea, depending on your philosophy.

Your refactoring





Format Copy from initial code

or Cancel