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 */ free(ptr); /*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.
free(ptr); ptr = NULL;