Design a site like this with WordPress.com
Get started

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 */

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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

Create a free website or blog at WordPress.com.

Up ↑

%d bloggers like this: