Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be the output of the following C code?

#include <stdio.h>
    int main()
    {
        int i = 97, *p = &i;
        foo(&p);
        printf("%d ", *p);
        return 0;
    }
    void foo(int **p)
    {
        int j = 2;
        *p = &j;
        printf("%d ", **p);
    }

 

  • A.2 2
  • B.2 97
  • C.Undefined behaviour
  • D.Segmentation fault/code crash

Answer: A

Correct answer: 2 2

foo now takes a int ** and is given &p, so it can reach the caller's pointer itself. Assigning *p = &j changes main's p to point at j, and both prints show 2.

There is a hazard concealed in the output, though: j is local to foo and its lifetime ends when foo returns, so main's p is left dangling. The second print happens to find 2 still in that stack location, but reading it is undefined behaviour.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.