Question
Consider the following C code:
#include <stdio.h>
#include <stdlib.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:
Official answer and solution
- Official answer
- D
- From
- Official GATE 2017 answer key
Solution
Trace the memory allocations and pointer assignments in the program to identify resource management issues.
Trace the execution of main():
int *x = malloc(sizeof(int));: A dynamic block of memory (say Block 1) is allocated on the heap, and its address is stored inx.if (NULL == x) return;: Valid check; since allocation succeeds, execution proceeds.x = assignval(x, 0);: Stores value 0 into Block 1 and returnsx.if (x): Sincexis non-NULL, the condition is true.- Inside the
ifblock:
x = (int *)malloc(sizeof(int));
A second block of memory (say Block 2) is allocated on the heap. The returned address is assigned tox, completely overwriting the address of Block 1!
Because no other pointer holds the address of Block 1, Block 1 is now orphaned and cannot be accessed or deallocated. This is the definition of a memory leak.
At the end of main(), free(x); only frees Block 2. Block 1 remains allocated until the process terminates. Hence, the code compiles successfully but results in a memory leak.
D
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2017 Computer Science and Information Technology (CS) Session 1
- Question
- 13 of 65, printed as CS Q.13
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.