GATE 2017 CS – Question 23
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:
Practise this question in The GATE Grind →
Show answer and explanation
Correct answer: (D) compiles successfully but execution may result in memory leak
Explanation
The code compiles. The first `malloc` result is stored in `x`, and then `x` is overwritten by a second `malloc` without freeing the first block. That first block is lost, which is a memory leak.