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 = (int*)malloc(sizeof(int));
*j = 10;
return j;
}

 

  • A.10
  • B.Compile time error
  • C.Segmentation fault/runtime crash since pointer to local variable is returned
  • D.Undefined behaviour

Answer: A

Correct answer: 10

The storage was obtained from malloc, so it lives on the heap and survives the return of the function that allocated it. The pointer therefore remains valid in main and dereferencing it gives 10. Compare the next question, where the same structure with an automatic variable is undefined - the difference is the storage duration, not the pointer.

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

Post your comment

Please log in or register to post a comment.