ProgrammingHard

A pointer p is freed with free(p) and then set to NULL. Why is this safer than leaving it dangling?

  1. A. It frees the block a second time, which reclaims more memory
  2. B. A later free(p) or a read through p becomes a defined no-op or an explicit NULL check, instead of undefined behaviour
  3. C. It moves the block to the stack
  4. D. It prevents the compiler from optimising the code

Correct answer: B. A later free(p) or a read through p becomes a defined no-op or an explicit NULL check, instead of undefined behaviour

Setting the pointer to NULL turns later accidental uses into safe checks. A second free of the same pointer would still be undefined.

More C Programming questions

Exams that ask this topic