Search code examples
cfree

How do you free a 2D malloc'd array in C?


I'm creating a 2D Array in C; am I freeing it correctly?

// create
int n = 3;
int (*X)[n] = malloc(sizeof(int[n][n]));

// set to 0
for(int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
        X[i][j] = 0;
    }
}   

// is this all I need?
free(X);

Solution

  • You must call free once for each malloc. Your code has one malloc and one free (with the same address) so it is correct.