Dangling Pointers in C++

Dangling pointers

Dangling pointers arise when an object is destroyed. Despite being deleted or de-allocated, it still has an incoming reference because the value of the pointer was not modified. The pointer still points to the memory location of the de-allocated memory.

AVOID DANGLING POINTERS

It is easy to avoid dangling pointer errors by setting the pointer to NULL after de-allocating the memory, so that the pointer no longer stays dangling. Assigning NULL value to the pointer means it is not pointing to any memory location.

char **Ptr;
char *str = "Hi";	
Ptr = &str;
free (str);  /* Ptr now becomes a dangling pointer as str has been freed and Ptr is pointing to a de-allocated memory */
Ptr = NULL;   /* Ptr is no more dangling pointer */

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Blog at WordPress.com.

Up ↑

Design a site like this with WordPress.com
Get started