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, 10); } printf("%d\n", *x); free(x); } The code suffers from which one of the following problems: A. compiler error as the return of malloc is not typecast appropriately B. compiler error because the comparison should be made as x == NULL and not NULL == x C. compiles successfully but execution may result in a dangling pointer D. compiles successfully but execution may result in memory leak

GATE 2017 · Programming and Data Structures · Pointers · medium

Answer: The code compiles successfully but execution results in a memory leak. Answer: D.

  1. Check for compiler errors: In C, NULL == x is identical to x == NULL (Yoda condition, valid). malloc does not require an explicit cast in C (unlike C++). So options A and B are incorrect — no compiler errors.
  2. Trace execution for dangling pointer: A dangling pointer would require freeing x and then using it. The program never frees x before the final free(x), so no dangling pointer exists. Option C is incorrect.
  3. Identify memory leak: Flow: x = malloc (block1, addr A). assignval sets *x=0. if(x) is true (x != NULL). Inside: x = malloc (block2, addr B). Now x = B; addr A is lost. assignval sets *x=10. printf prints 10. free(x) frees block2. Block1 (addr A, value 0) is NEVER freed. This is a memory leak.