How to free a 2d array of structs in c99

3443 views c
2

This is how I create the 2d array.

   Space **create_map( int row, int col) {
        Space **map = malloc(row * sizeof(Space*));
        for (int i = 0; i < row; ++i)
            map[i] = malloc(sizeof(Space) * col);
        return map;
    }

This is the components of the struct

typedef struct Space{
    char character;
    int isVisited;
    int row;
    int column;
    int stepCount;
}Space;

How would I free this?

answered question

generally work backwards in the order of mallocs. free each map[i] then free map

This must have a duplicate — the problem, as ever, is finding it. It's often easier to answer than to find the duplicate, which probably means it is easier to ask than to find another question already asked with suitable answers. Oh well, maybe that's philosophy for MSO rather than SO.

Incidentally, the answer is the same for C89/90 and C11 (and C17/C18) — for the allocation shown, there's basically one way to do the freeing accurately.

1 Answer

1

You need to free the memory in "reverse" from when you allocated it. So firstly, you need to free the elements of the array (or other struct), and then free the pointer.

void freeMap(Space map){
    for (int i = 0; i < row; ++i)
        free(map[i]);
    free(map);
}

posted this

Have an answer?

JD

Please login first before posting an answer.