C memory lifetime — what is printed when returning a pointer to a local array?\n\n/* program */\n#include<stdio.h>\n#include<string.h>\n\nint main()\n{\n char *s;\n char *fun();\n s = fun();\n printf("%s\n", s);\n return 0;\n}\n\nchar fun()\n{\n char buffer[30];\n strcpy(buffer, "RAM");\n return buffer; / returning address of a local array */\n}\n\nPredict the output.

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:

  • 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

More Questions from Memory Allocation

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion