C memory lifetime — what is printed when returning a pointer to a local array?
/* program */
#include
#include
int main()
{
char *s;
char *fun();
s = fun();
printf("%s
", s);
return 0;
}
char fun()
{
char buffer[30];
strcpy(buffer, "RAM");
return buffer; / returning address of a local array */
}
Predict the output.
-
A0xffff
-
BGarbage value
-
C0xffee
-
DError
Answer
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:
- buffer is a local char array in fun with automatic storage duration.
- fun returns buffer's address to main.
- main then prints the string at that stale address.
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:
1) buffer[30] is created on the stack inside fun.2) After return, the stack frame is invalidated; buffer no longer exists.3) s in main holds an invalid/dangling pointer.4) printf reads memory via s, producing unpredictable characters or behavior.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:
- Specific hex addresses (0xffff, 0xffee): These are arbitrary guesses; output is not a fixed address string.
- Error: Most compilers only warn; the code often still compiles.
Common Pitfalls:Assuming a successful run implies correct code. Undefined behavior may seem to work during tests, masking serious bugs.
Final Answer:Garbage value