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;
}
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.
Please log in or register to report this question.