25. What will be the output of following code :
// Assume all header files are included
main()
{
int *ptr;
ptr=(int*)malloc(256*256-1);
if(ptr==NULL)
printf("Memory allocation fails");
else
printf("Memory allocation successful");
}
A. Memory allocation fails
B. Memory allocation successful
C. Compilation Error
D. Runtime Error
View Answer & Explanation
Ans. A
256*256=65536 exceeded the range of integer and hence wrap around takes place and value of 256*256 becomes 0. Now (256*256-1) will become (0-1) = -1. So the malloc in line ptr=(int*)malloc(-1) becomes fail to create memory as the size is negative, and returns NULL.
26. What will be the output of following code :
// Assume all header files are included
main()
{
int *ptr;
ptr=(int*)malloc(256*256L-1);
if(ptr==NULL)
printf("Memory allocation fails");
else
printf("Memory allocation successful");
}
A. Memory allocation fails
B. Memory allocation successful
C. Compilation Error
D. Runtime Error
View Answer & Explanation
Ans. b
256*256L=65536 can be stored in long int. Here 256L means long int. Hence (65536-1) = 65535 bytes (64KB-1) memory will be allocated by malloc() successfully.
