Machine-translated by Google. Questions are authored in English.
Top

Discussion

How will you free the memory allocated by the following program?

#include <stdio.h>
#include <stdlib.h>
#define MAXROW 2
#define MAXCOL 3
int main()
{
    int **p, i, j;
    p = (int **) malloc(MAXROW * sizeof(int*));
    return 0;
}

 

  • A.memfree(int p);
  • B.dealloc(p);
  • C.malloc(p, 0);
  • D.free(p);

Answer: D

Correct answer: free(p);

Whatever malloc returned is what free must be given, so a single free(p) releases the block of row pointers.

Note what the program has actually allocated: only the array of MAXROW pointers, not the rows themselves. Had the loop allocating each row been present, every one of those blocks would need freeing individually before free(p) - releasing the outer array first would lose the addresses of the rows and leak them all.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.