Consider the following three C functions: [P1] int *g(void) { int x = 10;…

2001

Consider the following three C functions:

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

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

[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?

Answer: C. Only P1 and P2The correct answer is Option C (Only P1 and P2). In P1, x is a local automatic variable, so returning &x gives the caller a dangling pointer after the…

  1. A.

    Only P3

  2. B.

    Only P1 and P3

  3. C.

    Only P1 and P2

  4. D.

    P1, P2 and P3

Attempted by 73 students.

Show answer & explanation

Correct answer: C

The correct answer is Option C (Only P1 and P2). In P1, x is a local automatic variable, so returning &x gives the caller a dangling pointer after the function returns. In P2, px is declared but never initialized to point to valid memory; dereferencing *px is undefined behavior. In P3, memory is allocated using malloc before assigning through px, and returning that heap pointer is valid, although the caller should free it later.

Explore the full course: Iocl Engineers Officers Grade A Paper 2

Loading lesson…