What is a dangling pointer in C++?

Options

  • A. A pointer that points to a valid allocated object
  • B. A pointer that points to memory that is no longer valid
  • C. A pointer that always contains NULL
  • D. More than one of the above
  • E. None of the above

Correct Answer (Detailed Explanation is Below)

B. A pointer that points to memory that is no longer valid

Detailed Explanation

Answer: A pointer that points to memory that is no longer valid

A dangling pointer is a pointer whose referenced object or memory has already been destroyed or released.

For example:

int *p = new int(10);
delete p;

After delete p, the pointer variable may still contain the old address, but that memory is no longer valid for use. Such a pointer is called a dangling pointer.