Home » Programming & Data Structure » Programming and data structure miscellaneous » Question

Programming and data structure miscellaneous

Programming & Data Structure

  1. 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 :
    1. compiler error as the return of malloc is not typecast appropriately
    2. compiler error because the comparison should be made as x == NULL and not as shown
    3. compiles successfully but execution may result in dangling pointer
    4. compiles successfully but execution may result in memory leak
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.



Your comments will be displayed only after manual approval.