Skip to content
Official PYQ · 2001

GATE CS 2001 Q2.18 — Programming in C

Explain with AI

Consider the following three C functions:

[P1][P1] 

int *g(void)
{
    int x = 10;
    return (&x);
}

[P2][P2] 

int *g(void)
{
    int *px;
    *px = 10;
    return px;
}

[P3][P3] 

int *g(void)
{
    int *px;
    px = (int*) malloc (sizeof(int));
    *px = 10;
    return px;
}

Which of the above three functions are likely to cause problems with pointers?

Choose one option
View worked solution

Answer: C

To identify which functions cause pointer-related problems, let us analyze each function individually:

  1. Function P1P1:
    int *g(void)
    {
        int x = 10;
        return (&x);
    }

    The variable x is a local automatic variable allocated on the stack. When the function g() returns, its stack frame is deallocated, and x ceases to exist. Returning &x returns the address of a deallocated memory location, resulting in a dangling pointer. Accessing this pointer in the calling function leads to undefined behavior.

  2. Function P2P2:
    int *g(void)
    {
        int *px;
        *px = 10;
        return px;
    }

    The pointer px is declared but not initialized, meaning it contains a garbage address (wild pointer). Attempting to dereference it with *px = 10 writes to an arbitrary memory location, which typically causes a segmentation fault (undefined behavior).

  3. Function P3P3:
    int *g(void)
    {
        int *px;
        px = (int*) malloc (sizeof(int));
        *px = 10;
        return px;
    }

    This function dynamically allocates memory on the heap using malloc(). Heap-allocated memory persists until it is explicitly deallocated using free(). Therefore, returning px is perfectly safe and does not cause any immediate pointer-related errors (though the caller must eventually free it to avoid a memory leak).

Thus, only P1P1 and P2P2 cause pointer-related problems.

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

Published
Report a correction
Keep exploringMore Programming in C questions