How will you free the memory allocated by the following program?
#include <stdio.h>
#include <stdlib.h>
#define MAXROW 3
#define MAXCOL 4
int main()
{
int **p, i, j;
p = (int **) malloc(MAXROW * sizeof(int*));
return 0;
}
Answer: D
Correct answer: free(p);
The pointer that malloc returned is the one free must be given, so free(p) releases the block of row pointers.
Note what has actually been allocated: only the array of MAXROW pointers. Had the rows themselves been allocated in a loop, each would need freeing individually before free(p) - releasing the outer array first would destroy the only record of the row addresses and leak every one of them.
Please log in or register to report this question.