CameraIcon
CameraIcon
SearchIcon
MyQuestionIcon
MyQuestionIcon
1
You visited us 1 times! Enjoying our articles? Unlock Full Access!
Question

Consider the following C code:
#include <stdio.h>
int *assignval(int *x, int val)
{ *x = val;
return x;
}
void main( )
{ int* x = malloc (size of (int));
if (NULL = = x) return;
x = assignval(x, 0);
if(x)
{ x = (int*) malloc (size of (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:

A
compiles successfully but execution may result in dangling pointer
No worries! We‘ve got your back. Try BYJU‘S free classes today!
B
compiler error because the comparison should be made as x == NULL and not as shown
No worries! We‘ve got your back. Try BYJU‘S free classes today!
C
compiles scornfully but execution may result in memory leak
Right on! Give the BNAT exam to get a 100% scholarship for BYJUS courses
D
compiler error as the return of malloc is not typecast appropriately
No worries! We‘ve got your back. Try BYJU‘S free classes today!
Open in App
Solution

The correct option is C compiles scornfully but execution may result in memory leak
In main( ) function, malloc( ) function return a void type address. So no need of type casting i.e., (int*) malloc (size of (int));, inplace of type casting malloc (size of (int)); will not give compilation error. Assignval( ) function assign
0 in memory location pointed by ‘x’ and return address of memory location pointed by ‘x’. Since next malloc( ) function can take memory location assign by previous malloc( ) function
because there is no free(m) is given to freed previously assign memory location.
So this can give memory leak problem if variable 'x' non-zero value.

flag
Suggest Corrections
thumbs-up
0
Join BYJU'S Learning Program
similar_icon
Related Videos
thumbnail
lock
Liquids in Liquids and Raoult's Law
CHEMISTRY
Watch in App
Join BYJU'S Learning Program
CrossIcon