free a double pointer

Say you have a matrix mat

int** mat = malloc(10 * sizeof(int*));
for (int i=0; i<10; ++i) {
  mat[i] = malloc(10 * sizeof(int));
}

then you can free each row of the matrix (assuming you have initialized each correctly beforehand):

for (int i=0; i<10; ++i) {
  free(mat[i]);
}

then free the top-level pointer:

free(mat);

For your second question: if you allocate memory and use it, you will change that memory, which will not be “reverted” even if you free it (although you will not be able to access it reliably/portably any more).

Note: the top-level malloc is using sizeof(int*) as you are allocating pointer-to-ints, not ints — the size of int* and int are not guaranteed to be the same.

Leave a Comment