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

# include <stdio.h>

#i nclude < stdio.h >

#define MAXROW 3

#define MAXCOL 4

int main()

{

int ** p, i, j;

p = (int **)malloc (MAXROW* size of (int*));

return 0:

}

This question was previously asked in
UGC NET Computer Science (Paper 2) 17 June 2023 Official Paper
View all UGC NET Papers >
  1. memfree (int p);
  2. dealloc (p);
  3. malloc (p, 0);
  4. free (p):

Answer (Detailed Solution Below)

Option 4 : free (p):
Free
UGC NET Paper 1: Held on 21st August 2024 Shift 1
50 Qs. 100 Marks 60 Mins

Detailed Solution

Download Solution PDF

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.

Latest UGC NET Updates

Last updated on Jul 7, 2025

-> The UGC NET Answer Key 2025 June was released on the official website ugcnet.nta.ac.in on 06th July 2025.

-> The UGC NET June 2025 exam will be conducted from 25th to 29th June 2025.

-> The UGC-NET exam takes place for 85 subjects, to determine the eligibility for 'Junior Research Fellowship’ and ‘Assistant Professor’ posts, as well as for PhD. admissions.

-> The exam is conducted bi-annually - in June and December cycles.

-> The exam comprises two papers - Paper I and Paper II. Paper I consists of 50 questions and Paper II consists of 100 questions. 

-> The candidates who are preparing for the exam can check the UGC NET Previous Year Papers and UGC NET Test Series to boost their preparations.

Hot Links: teen patti master old version teen patti real money app teen patti party teen patti yes teen patti real cash apk