C after free — what does printing the pointer value show?\n\n#include<stdio.h>\n#include<stdlib.h>\n\nint main()\n{\n int *p;\n p = (int ) malloc(20); / Assume, for illustration, p held address 1314 /\n free(p);\n printf("%u", p); / Printing pointer with %u is itself non-portable /\n return 0;\n}\n\nWhat will be the output conceptually?

Difficulty: Medium

Correct Answer: Garbage value

Explanation:


Introduction / Context:
This question examines behavior after freeing dynamically allocated memory. It also highlights that printing pointers with %u is non-portable (the correct specifier is %p). The central concept is undefined behavior and dangling pointers.


Given Data / Assumptions:

  • p is freed using free(p).
  • The code then prints p's value with %u.
  • Assumed pre-free value 1314 is for illustration only.


Concept / Approach:
After free, p becomes a dangling pointer: its stored bits may remain the same, but using it is undefined behavior. Even reading or printing it in a non-portable manner can produce unpredictable results. Therefore, you cannot rely on seeing 1314 or any specific value. The robust practice is to set p = NULL after free and print with %p if needed.


Step-by-Step Solution:

1) Memory is released; p is not automatically nullified.2) Using p's value post-free is undefined; even printing it is not meaningful.3) Output may vary by run, compiler, and optimization.


Verification / Alternative check:
Setting p = NULL after free and then printing with printf("%p", (void)p) yields a consistent "(nil)" style representation on many systems, demonstrating defined behavior.


Why Other Options Are Wrong:

  • 1314/1316: Suggests a deterministic address; not guaranteed.
  • Random address: While colloquially similar, "Garbage value" better reflects UB in MCQ context.


Common Pitfalls:
Believing that free changes the pointer value or that printing a freed pointer is safe. Always invalidate the pointer explicitly.


Final Answer:
Garbage value

Discussion & Comments

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