Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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

  • Difficulty Level : Basic
  • Last Updated : 28 Jun, 2021

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.

Attention reader! Don’t stop learning now.  Practice GATE exam well before the actual exam with the subject-wise and overall quizzes available in GATE Test Series Course.

Learn all GATE CS concepts with Free Live Classes on our youtube channel.

 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

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!