What is Dangling Pointer in C

Interview Questions
  • What is Dangling Pointer in C

What is Dangling Pointer in C

A dangling pointer is a pointer which points to memory location where an object no longer exists. A dangling pointer comes into existence when we delete or de-allocate an object/variable without modifying the value of the incoming pointer, so that the pointer still points to the memory location of the deallocated memory.

Suppose a pointer 'ptr' is pointing to the address of an integer variable 'sum'. After some time variable 'sum' gets deleted but pointer ptr is still pointing to the same memory location.
Pointer ptr is unaware that variable sum got deleted. Now, pointer ptr became a Dangling pointer. If we try to access the memory location pointer by ptr, then we will get garbage value.

Here is an Example of Dangling pointer:

/* Dynamically allocating memory for an integer variable */
int *ptr = (int*)malloc(sizeof(int));

/* ptr points to the memory location of dynamically allocated int variable, 
Now, we will de-allocate earlier allocated memory using free  */

/*Now, ptr becomes a dangling pointer */
How to avoid the problem of dangling pointers ?

When ever we de-allocate/delete any object we should set all incoming pointers of this object to NULL.
ptr = NULL;

Related Topics
What is NULL pointer in C.
What is Wild pointer in C.
What is Address Of(&) Operator and Value Of(*) Operator in C.
What is size of void pointer in C
What is Memory leak in C and how can we avoid it.
What is difference between uninitialized(wild) pointer and null pointer
What is const pointer in C
What is pointer Arithmetic ? What are the valid and Invalid Pointer Arithmetic operations.
Why is default statement used in switch case in C
What is the use of sizeof() function in C