Gate2017 cs Q35

0. Consider the following C code:
# include
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:

  • Option : D
  • Explanation :
    A) is wrong. We don’t need to cast the result as void * is automatically and safely promoted to any other pointer type in this case.
    B) It is discarded for obvious reason.
    C) is wrong, because dangling pointer is nothing but the pointer which is pointing existing memory (deallocated or deleted memory) which is not happening here.
    D) is the answer. When you are calling malloc second time, new location is assigned to x and previous memory location is lost and now we don’t have no reference to that location resulting in memory leak.
Cancel reply

Your email address will not be published. Required fields are marked *


Cancel reply

Your email address will not be published. Required fields are marked *