Machine-translated by Google. Questions are authored in English.
Top

Discussion

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;
}

 

  • A.1314
  • B.Garbage value
  • C.1316
  • D.Random address

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.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.