-
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,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 :
-
- compiler error as the return of malloc is not typecast appropriately
- compiler error because the comparison should be made as x == NULL and not as shown
- compiles successfully but execution may result in dangling pointer
- compiles successfully but execution may result in memory leak
- compiler error as the return of malloc is not typecast appropriately
Correct Option: D
Consider all options.
1. In option (a), we don’t need to cast the, result as void * is automatically and safely promoted to any other pointer type in this case. So it is not correct.
2. In option (b), it is discarded for obvious reason, so it is also not correct.
3. In option (c), the dangling pointer is nothing but the pointer which is pointing to non-existing memory. (deallocated or deleted memory) which is not happening here, so it is also not correct.
4. In option (d), when you are calling malloc second time, then new location is assigned to X and previous memory location is lost and now we do not have no reference to that location, resulting in memory leak, so option (d) is correct.