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

Discussion

What is the output of this C code?

int *f();
int main()
{
int *p = f();
printf("%d\n", *p);
}
int *f()
{
int j = 10;
return &j;
}

 

  • A.10
  • B.Compile time error
  • C.Segmentation fault/runtime crash
  • D.Undefined behaviour

Answer: A

Correct answer: Undefined behaviour

j is an automatic variable whose lifetime ends when f returns, so the address returned is dangling and dereferencing it is undefined. It very often prints 10, because the stack frame has not yet been overwritten, but that is an accident rather than a guarantee - another call, a different optimisation level or a different compiler can produce anything at all. The preceding question shows the correct pattern, using malloc.

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

Post your comment

Please log in or register to post a comment.