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 3
#define MAXCOL 4

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);

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.

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

Post your comment

Please log in or register to post a comment.