Open In App

GATE | GATE-CS-2017 (Set 1) | Question 27

Like Article
Like
Save
Share
Report

Consider the following C code:

#include <stdio.h>

int * assignval (int *x, int val)
{
    *x = val;
    return x;
}

int main()
{
    int *x = malloc(sizeof(int));
    if (NULL == x) return;
    x = assignval(x, 0);
    if(x)
    {
        x = (int*) malloc(sizeof (int));
        if (NULL == x) return;
        x = assignval (x, 10);
    }
    printf("%d\n", *x);
    free(x);
}

The code suffers from which one of the following problems:
(A) compiler error as the return of malloc is not typecast appropriately.
(B) compiler error because the comparison should be made as x==NULL and not as shown.
(C) compiles successfully but execution may result in dangling pointer.
(D) compiles successfully but execution may result in memory leak.


Answer: (D)

Explanation: The code will run and give output = 10, so option A and B are discarded.

 int * x= malloc (sizeof(int));

This statement assigns a location to x. Now,

(int*)malloc(sizeof(int));

again assigns a new location to x , previous memory location is lost because now we have no reference to that location resulting in memory leak.

Therefore, option D is correct.

Memory leak occurs when programmers create a memory in heap and forget to delete it. Memory leaks are particularly serious issues for programs like daemons and servers which by definition never terminate.
Detailed article on Memory Leak

Running code of the question:




#include<stdio.h>
int *assignval (int *x, int val) 
{
    *x = val;
    return x;
}
  
void main () 
{
    int *x = malloc(sizeof(int));
    if (NULL == x) return;
    x = assignval (x,0);
    if (x)
    {
        x = (int *)malloc(sizeof(int));
        if (NULL == x) return;
        x = assignval (x,10);
    }
    printf("%d\n", *x);
    free(x);
}



Quiz of this Question


Last Updated : 28 Jun, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads