Skip to content
GATEiit

GATE CSE 2017 Session 1 Q23: C code with malloc and assignval: which problem occurs

Syllabus topic: Programming in C

Question

Consider the following C code:

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

The code suffers from which one of the following problems:

Try it: multiple choice: exactly one correct option

Select one option
Wrong answer costs 1/3 mark in GATE.
Show answer and explanation

Answer: D (official GATE 2017 final answer key)

Concept used: Overwriting the only pointer to a heap block without freeing it leaks that block; a void* from malloc needs no cast in C.

Concept notes

Loading notes…

First step: Trace x: after assignval(x,0) it is non-NULL, so the if-body runs and x is reassigned — ask what happens to the first allocated block.

Full step-by-step solution

Loading…

Answer from the official final answer key. Found a mistake? Use Report issue and we will fix it.

More questions on Programming in C

Every PYQ on this topic →

Share this question

WhatsAppDownload image

Source: official GATE 2017 Session 1 CS question paper and final answer key, organised by IIT Roorkee. Question paper · Answer key