C after free — what does printing the pointer value show?
#include
#include
int main()
{
int *p;
p = (int ) malloc(20); / Assume, for illustration, p held address 1314 /
free(p);
printf("%u", p); / Printing pointer with %u is itself non-portable /
return 0;
}
What will be the output conceptually?
-
A1314
-
BGarbage value
-
C1316
-
DRandom address
Answer
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