...
Question 5584 – NIELIT Junior Teachnical Assistant_2016_march
December 9, 2023
Question 6902 – Big-Data
December 9, 2023
Question 5584 – NIELIT Junior Teachnical Assistant_2016_march
December 9, 2023
Question 6902 – Big-Data
December 9, 2023

Question 7909 – Programming

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(size of(int));
                           if(NULL == x)  return;
                              x = assignval(x, 10);
                     }
                     printf("%dn",  *x);
                     free(x);
              }

The code suffers from which one of the following problems:

Correct Answer: D

Question 8 Explanation: 
Option A:
In C++, we need to perform type casting, but in C Implicit type casting is done automatically, so there is no compile time error, it prints10 as output.
Option B:
NULL means address 0, if (a == 0) or (0 == a) no problem, though we can neglect this, as it prints 10.
Option C:
x points to a valid memory location. Dangling Pointer means if it points to a memory location which is freed/ deleted.
int*ptr = (int*)malloc(sizeof(int));
free(ptr); //ptr becomes a dangling pointer
ptr = NULL; //Removing Dangling pointers condition
Option D:
x is assigned to some memory location
int*x = malloc(sizeof(int));
→ (int*)malloc(sizeof(int)) again assigns some other location to x, previous memory location is lost because no new reference to that location, resulting in Memory Leak.
Hence, Option D.
A
compiler error as the return of malloc is not typecast approximately
B
compiler error because the comparison should be made as x==NULL and not as shown
C
compiles successfully but execution may result in dangling pointer
D
compiles successfully but execution may result in memory leak
0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
error: Alert: Content selection is disabled!!