0

I have an exercise which asks me to free a 2D array, which was allocated with mallocs. I've already searched on stack and many websites but I'm still stuck.

I have to complete a function and then free the 2D array in arg. and make it to NULL.

void FreeMatrix(int*** ptab, int N){
   /// to complete
}

I already tried this but it doesnt work, and there is also 2 pictures that my teacher handed me to "help me" but I don't really understand it either.

for (int i = 0; i<N;i++){
   free(ptab[i]);
}
free(ptab);

=> The program crashes

Thanks for your help in advance :( The first image The second image

1 Answers1

1

Since you're using a 3 star pointer, you need an extra dereference in your function:

void FreeMatrix(int*** ptab, int N)
{
    for (size_t i=0; i<N; i++)
    {
        // *ptab is an int** type, and that makes (*ptab)[i] an
        // int* type. Presumably, you've malloced N int* types, so
        // free each of those
        free((*ptab)[i]);
    }

    // now free the initial int** allocation
    free(*ptab);
    // and set it to NULL per your requirements
    *ptab= NULL;
}

Working example

Note that 3-star pointers are generally considered bad design

yano
  • 4,827
  • 2
  • 23
  • 35