Difficulty: Easy
Correct Answer: Garbage value
Explanation:
Introduction / Context:
This question targets understanding of object lifetime and undefined behavior in C when returning addresses of automatic (stack) variables. It checks whether the learner recognizes that local arrays cease to exist once the function returns.
Given Data / Assumptions:
Concept / Approach:
Once fun returns, buffer's lifetime ends and the pointer value points to indeterminate storage. Accessing it (reading through it in printf("%s", s)) is undefined behavior and may display arbitrary data, crash, or appear to work by chance. There is no guaranteed, portable output.
Step-by-Step Solution:
Verification / Alternative check:
Correct fixes include making buffer static (static char buffer[30];) or allocating with malloc and returning the allocated pointer, then freeing it in main. Either approach gives a defined lifetime beyond fun's return.
Why Other Options Are Wrong:
Common Pitfalls:
Assuming a successful run implies correct code. Undefined behavior may seem to work during tests, masking serious bugs.
Final Answer:
Garbage value
Discussion & Comments