Consider the following C code: #include<stdio.h> int *assignval (int *x, int…

2017

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:

  1. A.

    compiler error as the return of malloc is not typecast appropriately.

  2. B.

    compiler error because the comparison should be made as x == NULL and not as shown.

  3. C.

    compiles successfully but execution may result in dangling pointer.

  4. D.

    compiles successfully but execution may result in memory leak.

Attempted by 149 students.

Show answer & explanation

Correct answer: D

Answer: the code compiles but may result in a memory leak.

Why:

  • The program allocates memory with malloc and stores the pointer in the variable.

  • Later the same pointer variable is assigned the result of a second malloc call, overwriting the original pointer value.

  • Because the original pointer was overwritten without calling free on it, the first allocated block becomes unreachable and is not freed — this is a memory leak.

  • The pointer that is printed and freed at the end refers to the second allocation, so there is no dangling pointer at that point.

How to fix:

  • Free the first allocation before overwriting the pointer. Example: free(x); x = malloc(sizeof(int));

  • Avoid allocating again if not necessary — reuse the existing allocation and just change its value with the helper function.

  • Additional good practices: include <stdlib.h> when using malloc to ensure the declaration is available, and declare main as int main(void) with an appropriate return value.

Summary: The primary problem is a memory leak caused by losing the pointer to the first allocated block when assigning a new allocation to the same pointer variable.

Explore the full course: Gate Guidance By Sanchit Sir