What is the purpose of setting a pointer to nullptr after deleting its dynamically allocated object?

Options

  • A. To allocate new memory automatically
  • B. To avoid leaving the pointer pointing to the released memory
  • C. To increase the size of the allocated memory
  • D. More than one of the above
  • E. None of the above

Correct Answer (Detailed Explanation is Below)

B. To avoid leaving the pointer pointing to the released memory

Detailed Explanation

Answer: To avoid leaving the pointer pointing to the released memory

After deleting dynamically allocated memory, the pointer can become a dangling pointer.

A common practice is:

delete p;
p = nullptr;

This makes the pointer explicitly point to no object. It also makes checking the pointer easier before later operations.