GATE / CS ARCHIVE

GATE CSE 2017 SET 1 / QUESTION 13

GATE CSE 2017 Set 1 Q13

Programming in C · Pointers & Memory · Full GATE CSE 2017 Set 1 paper

GATE 2017 Set 1, Q13 1 mark · MCQ
Report issue

Pointers & Memory

Question 13, GATE 2017: Printed C source:
#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); }
Choose A compiler error because malloc lacks a cast; B compiler error because NULL==x must be reversed; C compiles but may leave dangling pointer; D compiles but may leak memory. The missing stdlib.h and void main are literal source issues.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

Our answer: D under declared-library interpretation

1. Name the first allocated block A. If its allocation fails the function returns. Otherwise assignval(x,0) changes *x, not x: x still points to A and is nonnull.

2. Thus if(x) is entered even though the integer stored is zero. The second malloc result overwrites x, so no live variable retains A’s address.

3. If allocation B succeeds, printing/freeing uses B only. If it fails, the early return still does not free A. Either way after the second assignment A is leaked. This is intended D, subject to the source-declaration caveat below.

stdlib.h is omitted, so malloc/free lack their required declarations in modern C; void main is not a standard hosted entry point. The intended leak analysis assumes these routine issues are repaired, rather than endorsing option D’s literal “compiles successfully” wording.

Original paper, page 8 · Answer key