Solution
The correct answer is free(p);
Key PointsThe way to free the memory allocated by the given C program is option 4) free(p);.
The malloc function is used to dynamically allocate memory in the heap to store a 2D array (matrix) with MAXROW number of pointers to int.
#include <stdio.h>
#include <stdlib.h>
#define MAXROW 3
#define MAXCOL 4
int main() {
int **p, i, j;
// Allocate memory for MAXROW pointers to int
p = (int **)malloc(MAXROW * sizeof(int*));
// Allocate memory for each row
for(i = 0; i < MAXROW; i++) {
p[i] = (int *)malloc(MAXCOL * sizeof(int));
}
// Free memory for each row
for(i = 0; i < MAXROW; i++) {
free(p[i]);
}
// Finally, free the memory for the pointers
free(p);
return 0;
}
The fixed version of the program allocates the memory for each row in the array and then frees it sequentially before at the end, releasing the memory used for the array of pointers itself.