What will be the output of the program?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *p;
p = (int *)malloc(20); /* Assume p has address of 1314 */
free(p);
printf("%u", p);
return 0;
}
Answer: A
Correct answer: 1314
free takes its argument by value and does nothing to the caller's pointer. The bits in p are exactly what they were, so it still prints 1314.
That is precisely what makes a dangling pointer dangerous: it looks entirely valid, and dereferencing it may appear to work while the freed block is untouched. The conventional discipline is to set the pointer to NULL immediately after freeing, so that a later misuse fails loudly rather than silently.
Please log in or register to report this question.