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.


If your matrix isn't "ragged", i.e. all rows have the same length, you might want to consider:

  1. Accessing it manually, i.e. just treat it as a 1D array of values, and keep a separate width value. To access an element at (x,y) use mat[y * width + x].
  2. If you really want the convenience of mat[y][x], you can improve it by doing a single call to malloc() that allocates both the pointer array and all the rows, then initializing the pointers to point at each row. This has the advantage that it can all be free:ed with a single free(mat); call.

The second approach would look something like this:

double ** matrix_new(size_t width, size_t height)
{
  double **p = malloc(height * sizeof *p + width * height * sizeof **p);
  double *e1 = (double *) (p + height);
  size_t i;

  for(i = 0; i < height; ++i)
    p[i] = e1 + i * width;
  return p;
}

Note: the above is un-tested, and production code should obviously check for failure before using p.

Tags:

C

Pointers