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

Discussion

What is the output of this 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: Undefined behaviour

foo is given the address of the caller's pointer, so *p = &j does change main's p - that part works, and foo prints 2.

But j is an automatic variable of foo, and its lifetime ends when foo returns. main is then left with a dangling pointer, and *p is undefined behaviour. In practice the stack often still holds 2, which is why the value usually appears - but the compiler is entitled to assume the case never arises.

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

Post your comment

Please log in or register to post a comment.