Skip to content
Official PYQ · 2017

GATE CS 2017 Set 1 Q13 — Programming in C

Explain with AI

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:

Choose one option
View worked solution

Answer: D

To analyze the behavior of the given C code, let us trace its execution step-by-step:

  1. First Allocation:
    int *x = malloc(sizeof(int));
    A block of memory (let's call it M1M_1) is allocated on the heap, and its address is stored in the pointer variable x.
  2. Assignment:
    x = assignval(x, 0);
    The value at M1M_1 is set to 0, and x continues to point to M1M_1.
  3. Second Allocation (Inside if (x) block):
    x = (int *)malloc(sizeof(int));
    A new block of memory (let's call it M2M_2) is allocated on the heap, and its address is assigned to x.
    At this point, the address of the first block M1M_1 is overwritten and lost. Since there is no other pointer referencing M1M_1, this memory block can never be accessed or freed. This is a classic memory leak.
  4. Deallocation:
    free(x);
    Only the second block M2M_2 is freed. The first block M1M_1 remains allocated in the heap until the program terminates.

Evaluating the Options:

  • Option A is incorrect: In C, malloc returns a void* which is implicitly converted to any pointer type (like int*). No explicit typecasting is required, so there is no compiler error.
  • Option B is incorrect: The comparison NULL == x (often called a Yoda condition) is perfectly valid in C and prevents accidental assignment (e.g., writing x = NULL instead of x == NULL).
  • Option C is incorrect: A dangling pointer is a pointer that points to a memory location that has already been deallocated. Here, x is freed at the very end of the function, and is not dereferenced after being freed.
  • Option D is correct: The code compiles successfully, but the loss of the reference to the first allocated block M1M_1 results in a memory leak.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Programming in C questions